我使用sass来表示stying元素,并对:和&:以及何时使用它们感到困惑。
有什么不同?我们应该在什么时候使用哪一个?
.root{
:first-child{
color: green;
}
&:first-child{
color: green
}
}哪种方法适合选择root容器的第一个子容器
发布于 2021-08-20 00:09:23
事实证明,没有:和&:
相反,有效的是&:
&:first-child{
color: green
}下面显示的一个是不带&的:是无效的
:first-child{
color: green;
}
//this one is an invalid code and doesn't work发布于 2021-08-20 00:16:12
ampersand & is the "parent selector" in Sass,并将其后面的规则附加到包含父作用域。但是,您拥有的这两条规则都不起作用。第一个...
.root{
:first-child{
color: green;
}
}...would呈现到CSS...
.root :first-child{
color: green;
}...which将是无效的CSS,因为:first-child pseudo-class期望附加到实际的CSS选择器。
第二个...
.root{
&:first-child{
color: green
}
}...would呈现为CSS ...
.root:first-child{
color: green
}...but这条规则等同于“.root类的第一个孩子应该是绿色的”,这并不是你想要的。
对于您想要的--“选择根容器的第一个孩子”,您可能需要这个CSS:
.root > *:first-child {
color: green;
}<div class="root">
<p>some content</p>
<div>
<ul>
<li>some</li>
<li>other</li>
<li>content</li>
</ul>
</div>
</div>
...which等同于“具有.root类的容器中任何类型的第一个直接派生。
.root {
>* {
&:first-child {
color: green;
}
}
}我可能会把它简化为...but。
.root {
>*:first-child {
color: green;
}
}https://stackoverflow.com/questions/68850640
复制相似问题