Writing CSS used to mean lots of repetition. For years, we had to write long selectors to style nested elements. Now, native CSS nesting changes everything.
I used SCSS for years just to get nesting in my CSS. But now browsers support nesting right out of the box. No build tools needed. Let me show you how it works.
Nesting
Baseline 2023 newly available
Supported in Chrome: yes.
Supported in Edge: yes.
Supported in Firefox: yes.
Supported in Safari: yes.
Since December 2023 this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Remember writing CSS like this?
Now we can write it like this:
The nested version is more concise and shows the relationship between elements more clearly. The indentation reflects the DOM structure.
CSS nesting works with any valid selector. Here’s how you can nest different types:
The &
symbol represents the parent selector. It’s particularly useful for modifiers and pseudo-classes:
You can nest media queries too, keeping related styles together:
Browser Support and Fallbacks
As of late 2023, CSS nesting is supported in all major browsers. Still, if you need to support older browsers, you have options:
- Use @supports to provide fallbacks
- Use a CSS preprocessor
- Use PostCSS with the nesting plugin
Here’s how you can use @supports to provide a fallback:
Best Practices
While nesting is powerful, it’s important to use it judiciously:
- Avoid deep nesting (more than 3 levels) as it can make styles hard to maintain
- Use BEM or similar naming conventions to keep specificity in check
- Consider the output CSS and performance implications
- Keep selectors as shallow as possible