在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)
今天你可以使用像这样的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,join和append)来创建所需的选择器序列.然后使用@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)
您需要在{}中包含@ at-root内容
.wrapper {
h1 {
@at-root {
.wrapper .active h1 {
color: red;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)