CodeBlanks Logo Icon CodeBlanks

& nesting selector

CSS course · Expert · Lesson 44/53

Learn the & nesting selector.

The & nesting selector

Inside a nested block, the & sign stands for the full name of the outer selector. It is called the nesting selector. Writing .button { &:hover { color: navy; } } means the same as .button:hover { color: navy; }.

Without & the browser joins selectors with a space: .button { :hover { } } wrongly becomes .button :hover, which means a hover on a child inside the button. & keeps the target correct.

When is & required?

For a descendant relationship, & is not required: .card { p { } } already yields .card p. But for pseudo-classes, pseudo-elements and suffixes, & is essential.

For instance .btn { &-primary { } } produces the .btn-primary selector. This brings BEM-style naming into plain CSS without a preprocessor.

Exercise Add hover and primary to the button

Add two nested blocks inside the .btn selector: first &:hover with color: navy; second &-primary suffix selector with background: blue.

Show example solution
Add two blocks inside .btn.
Example solution:
/* add hover and primary inside .btn */
.btn {
  border: none;
  &:hover {
    color: navy;
  }
  &-primary {
    background: blue;
  }
}

Test yourself

  1. Write &:hover

    .button {
      ____ {
        color: navy;
      }
    }
    Show answer
    .button {
      &:hover {
        color: navy;
      }
    }
  2. What does & represent?

    .button {
      &:hover { color: navy; }
    }
    • The full name of the outer selector (.button)
    • Every element on the page
    • Only the text inside the button
    • The next sibling element
    Show answer

    The full name of the outer selector (.button) — Correct. & stands for the outer .button selector; &:hover becomes .button:hover.

  3. Match each nesting snippet to its meaning

    .card { p { } }
    .card p
    .card { &:hover { } }
    .card:hover
    .btn { &-primary { } }
    .btn-primary
    .card { &.active { } }
    .card.active

All lessons in Expert