The CSS 'nesting' selector (&) - Why would I need it?

What is it?

  • It is a “nesting selector”
  • It is relatively new, as of 2023 has widespread support across the major browsers.
  • It’s basically used to repeat the parent.

Example

/*css*/
div {
    background-color: black;
    padding: 100px;

    &:hover {
       color: green;
    }
}

is equivalent to writing:

/*css*/
div {
    background-color: black;
    padding: 100px; 
}
div:hover {
   color: green;
}

But I could simply do this?

/*css*/
div {
    background-color: black;
    padding: 100px;

    :hover {
      color: green;
    }
}

Wrong. That won’t work…because css would interpret the above as adding a white space between the div and the :hover

/*css*/
div {
    background-color: black;
}
div :hover {  
   color: green;
}

(Please note the white space between div and hover: i.e. div hover above. Of course if you did that, it would no longer work as intended.)

…and that will not work the same. Why not? Because now the hover will only apply when when you hover over the p tag, rather than the div tag. And we don’t want that.

& allows you to eliminate the white space that would other be created if you used the standard nesting.

Try experimenting with the above set-up here on codepen.

Written on January 4, 2025