Sass .scss:嵌套和多个类?

我正在为我当前的项目使用Sass (.scss)。

下面的例子:

超文本标记语言

<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将是蓝色的。

我如何用Sass在container内嵌套这个?

435317 次浏览

你可以使用父选择器引用 &,它将在编译后被父选择器替换:

举个例子:

.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&的连接会抛出一个错误。

如果是这种情况,我认为您需要使用更好的方法来创建类名或类名约定。例如,就像你说的,你想要.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方法。你可以检查这个链接:块元素修正方法

Christoph的回答很完美。然而,有时你可能想上更多的课。在这种情况下,你可以尝试@at-root#{} css特性,这将允许两个根类使用&彼此相邻。

这将不起作用(由于nothing before &规则):

container {
background:red;
color:white;
    

.desc& {
background: blue;
}


.hello {
padding-left:50px;
}
}

但这将(使用@at-root plus #{&}):

container {
background:red;
color:white;
    

@at-root .desc#{&} {
background: blue;
}


.hello {
padding-left:50px;
}
}

使用&

SCSS

.container {
background:red;
color:white;


&.hello {
padding-left:50px;
}
}

https://sass-lang.com/documentation/style-rules/parent-selector

除了Cristoph的回答,如果您想在声明中更具体,您可以引用容器类组件的所有子组件。这可以用:

.container {
// ...
#{&}.hello {
padding-left: 50px;
}
}

编译为:

.container .container.hello {
padding-left: 50px;
}

希望这对你有帮助!

这对我很有效

<div class="container">
<div class="desc">
desc
</div>
<div class="asc">
asc
</div>
</div>


.container{
&.desc {
background: blue;
}
&.asc {
background: red;
}
}