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

Does sass support to use parent selector as follows?

问题

我主要使用以下几种方法。 (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 }

想知道有没有这个功能。谢谢。

我的结果

我从@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 似乎支持我想要的父选择器。

很遗憾,没有。我认为您给出的第一个例子是实现这一目标的最佳方式。另一种选择可能是:

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

它将产生与您想要的相同的编译结果。但要注意嵌套 .head class。它会绊倒你。

Sass 中没有 "parent" 选择器,但是,在您的情况下,您可以使用棘手的 #{&} 插值和 @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;
}

下面并没有真正使用父选择器。只需使用 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;
}