CSS Nesting
Use modern CSS nesting to group related selectors together without relying on a preprocessor.
Use modern CSS nesting to group related selectors together without relying on a preprocessor. This hands-on tutorial focuses on practical implementation of css nesting concepts.
CSS Nesting
CSS nesting lets you write related selectors together in native CSS. It can improve readability when used with restraint.
A Simple Example
.card {
padding: 1rem;
border-radius: 1rem;
& h2 {
margin-top: 0;
}
&:hover {
box-shadow: 0 12px 24px rgba(15, 23, 42, 0.12);
}
}
The & refers to the current selector, which makes hover states and child relationships easier to read in one place.
Why Nesting Helps
- related rules stay grouped together
- component states become easier to scan
- repetitive selector prefixes are reduced
Where Nesting Goes Wrong
Nesting becomes a problem when it turns into deep selector chains.
Avoid patterns like:
.page {
& .section {
& .card {
& .title {
color: #0f172a;
}
}
}
}
If you need that much structure, the component naming likely needs improvement.
Best Practices
- keep nesting shallow
- use it mostly for states and nearby descendants
- prefer classes over long structural chains
- stop nesting when readability drops
Next Step
Continue to Subgrid to align nested layouts with the same track system as their parent grid.