在 SASS (SCSS) 中,加号 (+
) 和与号 (&
) 是嵌套规则中的特殊语法,它们用于处理选择器的相对关系和组合。
+
)加号用于选择紧接在另一个选择器之后的兄弟元素。这在编写相邻兄弟选择器时非常有用。例如:
button {
// ...button styles...
+ p {
// 这里的样式只会应用在紧跟在 button 元素之后的第一个 <p> 元素上
margin-top: 10px;
}
}
编译后的 CSS 将会是:
button {
/* ...button styles... */
}
button + p {
margin-top: 10px;
}
&
)与号用于在选择器内部引用父选择器。这在嵌套规则中非常有用,尤其是当你需要构建复杂的选择器时。例如:
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
li {
display: inline-block;
&:hover {
// 这里的 & 代表 li 元素,所以编译后的 CSS 选择器将是 li:hover
background-color: #eee;
}
}
}
}
编译后的 CSS 将会是:
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav ul li {
display: inline-block;
}
nav ul li:hover {
background-color: #eee;
}
在更复杂的例子中,&
可以帮助你构建包含父选择器的复杂选择器:
article[role="main"] {
width: 600px / 960px * 100%;
&:first-child {
font-size: 1em;
padding-bottom: 0.5em;
}
&:last-child {
font-size: 0.8em;
text-align: right;
}
}
编译后的 CSS 将会是:
article[role="main"] {
width: 62.5%;
}
article[role="main"]:first-child {
font-size: 1em;
padding-bottom: 0.5em;
}
article[role="main"]:last-child {
font-size: 0.8em;
text-align: right;
}
在这个例子中,&
代表 article[role="main"]
,所以你可以看到它被用在每个伪类的选择器中。
总结来说,加号 (+
) 用于选择紧随其后的兄弟元素,而与号 (&
) 用于在选择器内部引用父选择器,使得嵌套规则更加灵活和强大。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云