Visit homepage

CSS ampersand selector

  • Planted:

I’ve been using the CSS nesting selector, &, for a few years to nest style declarations. I wondered recently if you even need it. For example:

styles.css

button {
&:hover {
shadow: 2px 2px black;
}
:hover {
shadow: 2px 2px black;
}
}

The above CSS declarations are equivalent to:

styles.css

button:hover {
shadow: 2px 2px black;
}
button *:hover {
shadow: 2px 2px black;
}

Using the ampersand directly appends the selector that follows to the parent selector. So instead of matching the :hover state of all button children, we can use & to match hovering just the button itself.

So you do need it sometimes (which, like, why would it exist if you didn’t need it sometimes, I guess).

Reply