Nesting in CSS isn’t yet available in most browsers, but we can still do it using a pre-processor like PostCSS:
/* Get rid of link highlighting in article headings */.content {h1,h2,h3,h4,h5,h6 {a {@apply text-type-dark;}}}
Here I wanted to override the link styles for all the headings on my blog, and nesting came in extremely handy!
Without nesting, I would have had to specify this property for each heading level individually, and it would have been a mess. Especially since I only wanted to target the headings that are part of the content, not site-wide headings:
.content h1 a {@apply text-type-dark;}.content h2 a {@apply text-type-dark;}.content h3 a {@apply text-type-dark;}// ...you get the idea
Of course, until browsers get around to implementing this natively, this is exactly what this nested CSS compiles to. It’s like expanding the equation 2(a + b)
into 2a + 2b
.
But the key is that you don’t have to write it this way!
With PostCSS you can use the postcss-nesting plugin to make this happen.
If you’re using Nuxt 3 with TailwindCSS like I am, the Nuxt Tailwind module comes with this enabled by default!