以下 CSS 取自 Twitter Bootstrap 与号 (&) 字符是什么意思?
.clearfix {
*zoom: 1;
&:before,
&:after {
display: table;
content: "";
}
&:after {
clear: both;
}
}
那是 LESS,而不是 CSS。
此语法允许您嵌套选择器修饰符。
.clearfix {
&:before {
content: '';
}
}
将编译为:
.clearfix:before {
content: '';
}
使用
&
,嵌套选择器编译为 .clearfix:before
。.clearfix :before
。
嵌套
&
选择 SASS 和 LESS 中的父元素。它不仅仅适用于伪元素,它可以与任何类型的选择器一起使用。
例如
h1 {
&.class {
}
}
相当于:
h1.class {
}
这是一个 SCSS/LESS 示例:
a {
text-decoration: underline;
@include padding(15px);
display: inline-block;
& img {
padding-left: 7px;
margin-top: -4px;
}
}
以及 CSS 中的等效项:
a {
text-decoration: underline;
@include padding(15px);
display: inline-block;
}
a img {
padding-left: 7px;
margin-top: -4px;
}
'&' 在 Sass 和 Less 预处理器中都是有用的功能。用于嵌套。与 CSS 相比,它可以节省时间。
父选择器 & 是 Sass 发明的一种特殊选择器,它是 在嵌套选择器中用于引用外部选择器。
一种思考方式是,每当在 scss 中遇到 '&' 时,在 css 中构建时,它将被父选择器替换。
sass 文档中的一个很好的例子就是这个。
这个 sass 代码:
.alert {
// The parent selector can be used to add pseudo-classes to the outer
// selector.
&:hover {
font-weight: bold;
}
// It can also be used to style the outer selector in a certain context, such
// as a body set to use a right-to-left language.
[dir=rtl] & {
margin-left: 0;
margin-right: 10px;
}
// You can even use it as an argument to pseudo-class selectors.
:not(&) {
opacity: 0.8;
}
}
将编译为这个CSS:
.alert:hover {
font-weight: bold;
}
[dir=rtl] .alert {
margin-left: 0;
margin-right: 10px;
}
:not(.alert) {
opacity: 0.8;
}
https://sass-lang.com/documentation/style-rules/parent-selector/