根据这个主题:
Can I use the ampersand in SASS to reference specific tags with the parent class?
以下代码
[尝试1]
.specific-style {
color: red;
b& {
color: green;
}
span& {
color: blue;
}
}
应该返回
.specific-style {
color: red;
}
b.specific-style {
color: green;
}
span.specific-style {
color: blue;
}
但它给出了
"&" may only be used at the beginning of a compound selector.
[尝试2]
.specific-style {
color: red;
b#{&} {
color: green;
}
span#{&} {
color: blue;
}
}
返回
.specific-style {
color: red;
}
.specific-style b.specific-style {
color: green;
}
.specific-style span.specific-style {
color: blue;
}
[尝试3]
.parent {
.specific-style {
color: red;
@at-root b#{&}{
color: green;
}
@at-root span#{&} {
color: blue;
}
}
}
返回
.parent .specific-style {
color: red;
}
b.parent .specific-style {
color: green;
}
span.parent .specific-style {
color: blue;
}
到目前为止,这个是最接近的,但我忘了提及这应该适用于嵌套选择器,如下所示:
.parent .specific-style {
color: red;
}
.parent b.specific-style {
color: green;
}
.parent span.specific-style {
color: blue;
}
我的代码中是否有错误或者是Sass编译器错误?
答案 0 :(得分:2)
经过一些实验,您只需重复original answer
中提到的过程 .specific-style {
color: red;
@at-root b#{&}{
@at-root .parent #{&}{
color: green;
}
}
@at-root span#{&} {
@at-root .parent #{&}{
color: blue;
}
}
}
吐出
.specific-style {
color: red;
}
.parent b.specific-style {
color: green;
}
.parent span.specific-style {
color: blue;
}
但这似乎是一种复杂的做事方式。
答案 1 :(得分:1)
我想避免使用“占位符选择器”,但这是我解决这个问题的一种方式:
%colors {
color: red;
}
b%colors {
color: green;
}
span%colors {
color: blue;
}
@mixin colors{
@extend %colors;
};
.parent {
.specific-style {
@include colors;
}
}
<强>返回强>
.parent .specific-style {
color: red;
}
.parent b.specific-style {
color: green;
}
.parent span.specific-style {
color: blue;
}
\ O /