Sass&符号,选择临时父母?

Tim*_*ter 29 sass

在Sass中是否有办法使用&符选择直接父级,而不是整个组的父选择器?例如:

.wrapper{
    background-color: $colour_nav_bg;
    h1{
        color: $colour_inactive;
        .active &{
            color: red;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编译为:

.wrapper h1{
    color: grey;
}

.active .wrapper h1{
    color: red
}
Run Code Online (Sandbox Code Playgroud)

但我真正想要的是:

.wrapper .active h1{
    color: red;
}
Run Code Online (Sandbox Code Playgroud)

是这样编写SCSS的唯一选择吗?

.wrapper{
    background-color: $colour_nav_bg;
    h1{
        color: $colour_inactive;
    }
    .active h1{
        color: red;
    }
}
Run Code Online (Sandbox Code Playgroud)

HTML看起来像这样:

<ul class="wrapper">
    <li class="active">
        <h1>blah</h1>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

mya*_*uri 8

今天你可以使用像这样的mixin来解决这个问题:

@mixin if-direct-parent($parent-selector) {
  $current-sequences: &;
  $new-sequences: ();

  @each $sequence in $current-sequences {
    $current-selector: nth($sequence, -1);
    $prepended-selector: join($parent-selector, $current-selector);
    $new-sequence: set-nth($sequence, -1, $prepended-selector);
    $new-sequences: append($new-sequences, $new-sequence, comma);
  }

  @at-root #{$new-sequences} {
    @content;
  }
}
Run Code Online (Sandbox Code Playgroud)

由于&它本质上是一个列表列表,您可以使用列表函数(nth,set-nth,joinappend)来创建所需的选择器序列.然后使用@at-root在根级别输出新选择器.这是你如何使用它:

.grandparent-1,
.grandparent-2 {
  color: red;

  .child {
    color: blue;

    @include if-direct-parent('.parent') {
      color: green;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

哪个会输出:

.grandparent-1,
.grandparent-2 {
  color: red;
}
.grandparent-1 .child,
.grandparent-2 .child {
  color: blue;
}
.grandparent-1 .parent .child, .grandparent-2 .parent .child {
  color: green;
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*dly 7

您需要在{}中包含@ at-root内容

.wrapper {
    h1 {
        @at-root {
           .wrapper .active h1 {
                color: red;
           }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Kat*_*ieK 6

在撰写本文时,没有用于元素的直接父代的Sass选择器。&如您所知,有哪个选择根父级。还有% 占位符选择器,它会隐藏规则直到扩展它。

Sass是开源的,因此您可以贡献一个新的“直接父级”选择器。

  • 这还没有实现吗? (2认同)