Skip to main content
CSS Tip

Be careful when using the nesting selector (&)

CSS Nesting is cool and using the "&" is a lifesaver BUT be careful. There's a gotcha!

⚠️ "&" in CSS is different from the one in Sass ⚠️

Your Sass code won't work the same way if you use it as a CSS code.

The below code won't give the same result when used with CSS Nesting and Sass

section {
p {
font-size: 20px;
.main & {
color: red;
}
}
}

Difference between Sass and CSS when using nesting

CSS Nesting introduces the :is() part which make the selection different: [Select any element that is descendant of .main AND is “section p” (p element descendant of section)]

Here are two demos using the same code but with a different setting.

See the Pen CSS nesting code by Temani Afif (@t_afif) on CodePen.

See the Pen Sass nesting code by Temani Afif (@t_afif) on CodePen.

The nesting selector can be desugared by replacing it with the parent style rule’s selector, wrapped in an :is() selector. ref


More CSS Tips