What does an "&" before a pseudo element in CSS mean?

CssTwitter BootstrapSassLess

Css Problem Overview


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;
  }
}

Css Solutions


Solution 1 - Css

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.

Solution 2 - Css

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 {

}

Solution 3 - Css

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;
   }

Solution 4 - Css

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneodymiumView Question on Stackoverflow
Solution 1 - CssSLaksView Answer on Stackoverflow
Solution 2 - CssanthonygoreView Answer on Stackoverflow
Solution 3 - CssRamesh kumarView Answer on Stackoverflow
Solution 4 - CssSudharshan SView Answer on Stackoverflow