正如在另一个问题中Stack Overflow 上提到的,MDN讲述了选择器的特殊性,我想通过 Sass 稍微增加我的选择器的权重以覆盖一些现有的样式。这是(编译的)CSS 的示例。
.parent .parent__child.parent__child { color: red; }
Run Code Online (Sandbox Code Playgroud)
它比仅用.parent .parent__child作选择器更具体。
我有办法通过 Sass 做到这一点,但我认为应该有更好的方法来做到这一点。我现在这样做的方法是:
.parent {
&__child.parent__child { color: red; }
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,这将是最好的设置(&符号必须直接相互连接,因为它不是子选择器):
.parent {
&__child&__child { color: red; }
}
Run Code Online (Sandbox Code Playgroud)
这会引发错误,并在“子”选择器之间添加一个点。在萨斯文档不说这个特定的情况下,任何东西。关于如何实现这一目标的任何想法?
编辑
我知道插值括号方法,但是如果选择器在三层中更深,例如四层中的三层,该怎么办?我只希望复制它的父选择器,而不是整个选择器树。
SASS 中有一个特殊的技巧,可以使用插值括号将特异性加倍(更多关于这里和这里的内容),因为&彼此相邻的两个是无效的 SASS 语法。
.parent {
&__child {
&#{&} {
color: red;
}
}
}
// compiles to
// .parent__child.parent__child { color: red; }
// You can also do this with deeper nested elements by
// prefacing the interpolation with the ancestor selectors:
.parent {
&__child {
.some .ancestor .elements &#{&} {
color: red;
}
}
}
// compiles to
// .some .ancestor .elements .parent__child.parent__child { color: red; }
Run Code Online (Sandbox Code Playgroud)
对于那些偶然发现并使用 LESS 的人,&&允许使用 double :
.parent {
&__child {
&& {
color: red;
}
}
}
Run Code Online (Sandbox Code Playgroud)