Sass .scss:嵌套和多个类?我正在使用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通常会red,但div.container.desc会是蓝色的。我如何container用Sass将其嵌入其中?
2 回答
Qyouu
TA贡献1786条经验 获得超11个赞
您可以使用父选择器引用 &,它将在编译后由父选择器替换:
对于你的例子:
.container {
background:red;
&.desc{
background:blue;
}}/* compiles to: */.container {
background: red;}.container.desc {
background: blue;}该&会彻底解决,因此,如果你的父母选择嵌套本身,嵌套将更换前解决&。
这种表示法最常用于编写伪元素和类:
.element{
&:hover{ ... }
&:nth-child(1){ ... }}但是,您可以放置&几乎任何您喜欢的位置*,因此也可以使用以下内容:
.container {
background:red;
#id &{
background:blue;
}}/* compiles to: */.container {
background: red;}#id .container {
background: blue;}但请注意,这会以某种方式破坏您的嵌套结构,从而可能会增加在样式表中查找特定规则的工作量。
*:在前面不允许有空格以外的其他字符&。所以你不能直接连接selector+ &- #id&会抛出错误。
幕布斯6054654
TA贡献1876条经验 获得超7个赞
如果是这种情况,我认为您需要使用更好的方法来创建类名或类名约定。例如,就像你说的那样,你希望.container课程根据具体的用法或外观有不同的颜色。你可以这样做:
SCSS
.container {
background: red;
&--desc {
background: blue;
}
// or you can do a more specific name
&--blue {
background: blue;
}
&--red {
background: red;
}}CSS
.container {
background: red;}.container--desc {
background: blue;}.container--blue {
background: blue;}.container--red {
background: red;}上面的代码基于类命名约定中的BEM方法。您可以查看以下链接:BEM - 块元素修改器方法
添加回答
举报
0/150
提交
取消
