我正在为我的当前项目使用sass(.scss(。
html
<div class="colours colours--blue">
<!-- This should be blue -->
</div>
<div class="colours colours--yellow">
<!-- This should be yellow -->
</div>
<div class="colours colours--blue colours--yellow">
<!-- This should be green -->
</div>
scss
.colours {
width: 50px;
height: 50px;
&--blue {
background-color: blue;
}
&--yellow {
background-color: yellow;
}
&--blue (AND) &--yellow { /* <<< HOW TO CREATE THIS SELECTOR? */
background-color: green;
}
}
请记住,&
的作用几乎就像Sass中的占位符一样。提出,只使用插值util #{}
避免字符串串联会更容易。
因此,答案将与此一样直截了当:
.colours {
width: 50px;
height: 50px;
&--blue {
background-color: blue;
}
&--yellow {
background-color: yellow;
}
&--blue#{&}--yellow {
background-color: green;
}
}
工作演示
您可以使用选择器函数:
@at-root #{selector-unify(selector-append(&, "--blue"), selector-append(&, "--yellow"))} {
background-color: green;
}
可能最好将其包裹在另一种混合物中,以便更容易使用:
@mixin both-colours($a, $b) {
@at-root #{selector-unify(selector-append(&, "--#{$a}"), selector-append(&, "--#{$b}"))} {
@content;
}
}
用作
@include both-colours(blue, yellow) {
background-color: green;
}
也许考虑使用类似于下面的变量:
$c:'.colours';
#{$c} {
width: 50px;
height: 50px;
&--blue {
background-color: blue;
}
&--yellow {
background-color: yellow;
}
&--blue {
&#{$c}--yellow {
background-color: green;
}
}
}