Sass .scss:嵌套和多个类? [英] Sass .scss: Nesting and multiple classes?
问题描述
我在当前项目中使用 Sass (.scss).
以下示例:
HTML
<div class="你好">你好,世界
SCSS
.container {背景:红色;白颜色;.你好 {填充左:50px;}}
这很好用.
我可以在使用嵌套样式时处理多个类吗.
在上面的示例中,我正在谈论这个:
CSS
.container.desc {背景:蓝色;}
在这种情况下,所有 div.container
通常都是 red
,但 div.container.desc
会是蓝色.
如何将其嵌套在 container
与 Sass 中?
您可以使用 parent选择器引用 &
,编译后会被父选择器替换:
例如:
.container {背景:红色;&.desc{背景:蓝色;}}/* 编译为: */.容器 {背景:红色;}.container.desc {背景:蓝色;}
&
将完全解析,因此如果您的父选择器本身是嵌套的,则在替换 &
之前将解析嵌套.
这种表示法最常用于编写伪元素和-classes:
.element{&:hover{ ... }&:nth-child(1){ ... }}
但是,您几乎可以将 &
放在您喜欢的任何位置*,因此以下也是可能的:
.container {背景:红色;#id &{背景:蓝色;}}/* 编译为: */.容器 {背景:红色;}#id .container {背景:蓝色;}
但是请注意,这会以某种方式破坏您的嵌套结构,因此可能会增加在样式表中查找特定规则的工作量.
*:&
前不允许有除空格外的其他字符.所以你不能直接连接 selector
+&
- #id&
会抛出错误.
I'm using Sass (.scss) for my current project.
Following example:
HTML
<div class="container desc">
<div class="hello">
Hello World
</div>
</div>
SCSS
.container {
background:red;
color:white;
.hello {
padding-left:50px;
}
}
This works great.
Can I handle multiple classes while using nested styles.
In the sample above I'm talking about this:
CSS
.container.desc {
background:blue;
}
In this case all div.container
would normally be red
but div.container.desc
would be blue.
How can I nest this inside container
with Sass?
You can use the parent selector reference &
, it will be replaced by the parent selector after compilation:
For your example:
.container {
background:red;
&.desc{
background:blue;
}
}
/* compiles to: */
.container {
background: red;
}
.container.desc {
background: blue;
}
The &
will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the &
.
This notation is most often used to write pseudo-elements and -classes:
.element{
&:hover{ ... }
&:nth-child(1){ ... }
}
However, you can place the &
at virtually any position you like*, so the following is possible too:
.container {
background:red;
#id &{
background:blue;
}
}
/* compiles to: */
.container {
background: red;
}
#id .container {
background: blue;
}
However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.
*: No other characters than whitespaces are allowed in front of the &
. So you cannot do a direct concatenation of selector
+&
- #id&
would throw an error.
这篇关于Sass .scss:嵌套和多个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!