114

In the following CSS taken from Twitter Bootstrap what does the ampersand (&) character mean?

.clearfix {
  *zoom: 1;
  &:before,
  &:after {
    display: table;
    content: "";
  }
  &:after {
    clear: both;
  }
}
j08691
  • 204,283
  • 31
  • 260
  • 272
neodymium
  • 3,686
  • 6
  • 23
  • 31

4 Answers4

140

That's LESS, not CSS.

This syntax allows you to nest selector modifiers.

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

Will compile to:

.clearfix:before {
  content: '';
}

With the &, the nested selectors compile to .clearfix:before.
Without it, they compile to .clearfix :before.

Dave Mackey
  • 4,306
  • 21
  • 78
  • 136
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
38

A nested & selects the parent element in both SASS and LESS. It's not just for pseudo elements, it can be used with any kind of selector.

e.g.

h1 {
    &.class {

    }
}

is equivalent to:

h1.class {

}
anthonygore
  • 4,722
  • 4
  • 31
  • 30
  • when encountering such code it could also be https://github.com/postcss/postcss-nested – Dill Feb 17 '23 at 08:27
18

Here is an SCSS/LESS example:

a {
   text-decoration: underline; 
   @include padding(15px);
   display: inline-block;

     & img  {
                padding-left: 7px;
               margin-top: -4px;
             }
 }

and its equivalent in CSS:

a {
  text-decoration: underline; 
  @include padding(15px);
  display: inline-block;
}

a img  {
     padding-left: 7px;
     margin-top: -4px;
   }
Remolten
  • 2,614
  • 2
  • 25
  • 29
Ramesh kumar
  • 518
  • 5
  • 8
3

'&' is useful feature in both Sass and Less preprocessor. For nesting it's used. It is time saver when we compare to CSS.

Sudharshan S
  • 89
  • 1
  • 8