我在当前项目中使用 Sass (.scss)。
以下示例:
HTML
<div class="container desc">
<div class="hello">
Hello World
</div>
</div>
SCSS
.container {
background:red;
color:white;
.hello {
padding-left:50px;
}
}
这很好用。
我可以在使用嵌套样式时处理多个类吗?
在上面的示例中,我正在谈论这一点:
CSS
.container.desc {
background:blue;
}
在这种情况下,所有 div.container
通常为红色
,但 div.container.desc
为蓝色。
如何使用 Sass 将其嵌套在 container
中?
最佳答案
您可以使用parent selector reference &
,编译后会被父选择器替换:
举个例子:
.container {
background:red;
&.desc{
background:blue;
}
}
/* compiles to: */
.container {
background: red;
}
.container.desc {
background: blue;
}
&
将完全解析,因此如果您的父选择器本身嵌套,则在替换 &
之前将解析嵌套。
此表示法最常用于写 pseudo-elements and -classes :
.element{
&:hover{ ... }
&:nth-child(1){ ... }
}
但是,您几乎可以将 &
放置在您喜欢的任何位置*,因此以下情况也是可能的:
.container {
background:red;
#id &{
background:blue;
}
}
/* compiles to: */
.container {
background: red;
}
#id .container {
background: blue;
}
但是请注意,这会在某种程度上破坏您的嵌套结构,因此可能会增加在样式表中查找特定规则的工作量。
*:&
前面除空格外不允许有其他字符。因此,您不能直接连接 selector
+&
- #id&
会抛出错误。
关于萨斯.scss : Nesting and multiple classes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11084757/