是否支持使用父选择器如下?

问题描述 投票:2回答:3

Problem

我主要使用以下方法。 (SASS)

.person {
    &.man {
        .head { A }
    }

    &.woman {
        .head { B }
    }

    .head { C }
}

但我想使用以下方法。 (SASS)

.person {
    .head {
        C

        <parent_selector.man> {
            A
        }

        <parent_selector.woman> {
            B
        }
    }
}

编译结果(CSS)

.person .head { C }
.person.man .head { A }
.person.woman .head { B }

我想知道是否有这样的功能。谢谢。

My result

我从@ falsarella的@ at-root方法中得到了这个想法。看起来有点粗糙,但这也是可能的。 (我实际上使用了比示例更深入的选择器,因此很难单独使用at-root和#{$}来解决。)

.person {
    $person: &;

    .head {
        C

        @at-root #{$person}.man .head {
            A
        }

        @at-root #{$person}.woman .head {
            B
        }
    }
}

或者它更方便和可读(如果父选择器不是一个简单的选择器。)通过命名$ parent并覆盖前一个$ parent来使用它。

当我考虑一次时,当前的选择器被命名为$ parent,因此令人困惑。最好忽略父选择器的'>',':after',...并将其命名为$ person。 (或创建命名约定。)

.earth {
    $parent: &;

    .person {
        $parent: &;

        .head {
            C

            @at-root #{$parent}.man .head {
                A
            }

            @at-root #{$parent}.woman .head {
                B
            }
        }
    }
}

由于进一步谷歌搜索,postcss似乎支持我想要的父选择器。

css sass selector
3个回答
4
投票

在Sass中没有“父”选择器,但是,在你的情况下,你可以使用一个棘手的#{&}插值和@at-root,如下所示:

.person {
    .head {
        color: white;

        @at-root .man#{&} {
            color: blue;
        }

        @at-root .woman#{&} {
            color: pink;
        }
    }
}

导致以下CSS:

.person .head {
  color: white;
}
.man.person .head {
  color: blue;
}
.woman.person .head {
  color: pink;
}

3
投票

不幸的是,没有。我认为你提供的第一个例子是实现这一目标的最佳方式。另一种选择可能是:

  .head {
    .person & {
      color: red;
    }
    .person.man & {
      color: blue;
    }
    .person.woman & {
      color: green;
    }
  }

它将根据您的需要生成相同的编译结果。但要注意嵌套.head类。它会绊倒你。


1
投票

以下并不真正使用父选择器。只需使用SASS @mixin来提供相同的CSS输出。

@mixin personHead($gender) {
    @if $gender == man {
        &.man .head{
            property: A; 
        }
    }
    @if $gender == woman {
        &.woman .head{
            property: B; 
        }
    }
    @if $gender == "" {
        .head{
            property: C; 
        }
    }
}

.person { @include personHead(man); }
.person { @include personHead(woman); }
.person { @include personHead(""); }


/* Compiled CSS Output */

.person.man .head {
    property: A;
}

.person.woman .head {
    property: B;
}

.person .head {
    property: C;
}
© www.soinside.com 2019 - 2024. All rights reserved.