91

在以下来自Twitter Bootstrap的 CSS 中,& 字符是什么意思?

.clearfix {
  *zoom: 1;
  &:before,
  &:after {
    display: table;
    content: "";
  }
  &:after {
    clear: both;
  }
}
4

4 回答 4

109

那是LESS,而不是 CSS。

此语法允许您嵌套选择器修饰符。

.clearfix { 
  &:before {
    content: '';
  }
}

将编译为:

.clearfix:before {
  content: '';
}

使用&,嵌套选择器编译为.clearfix:before.
没有它,它们将编译为.clearfix :before.

于 2012-11-28T15:43:54.480 回答
26

嵌套&选择 SASS 和 LESS 中的父元素。它不仅适用于伪元素,还可以与任何类型的选择器一起使用。

例如

h1 {
    &.class {

    }
}

相当于:

h1.class {

}
于 2016-03-23T00:08:11.933 回答
9

这是一个 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;
   }
于 2017-07-05T10:59:54.690 回答
1

'&' 在 Sass 和 Less 预处理器中都是有用的特性。用于嵌套。与 CSS 相比,它可以节省时间。

于 2021-10-28T06:18:11.763 回答