CSS Nesting (Native)
Native CSS nesting is here — no preprocessor needed! Nest selectors inside parent rules just like Sass/SCSS. It reduces repetition, groups related styles, and makes CSS more maintainable. Supported in all modern browsers since 2023.
CSS Nesting Rules
- & represents the parent — .card { & h2 { color: red; } } = .card h2 { color: red; }
- Implicit & — .card { h2 { } } works too, & is optional for descendant selectors
- & for pseudo-classes — .btn { &:hover { } } = .btn:hover { }
- & for pseudo-elements — .heading { &::after { } } = .heading::after { }
- Media queries nest too — .card { @media (min-width: 768px) { } } scopes the query to .card
- Multiple levels — Can nest deeply, but keep it to 2-3 levels for readability
- & at end — p { .dark & { color: white; } } = .dark p { color: white; }. Reverses the relationship
CSS Nesting Code
/* Without nesting — repetitive */
.card { background: white; border-radius: 12px; padding: 24px; }
.card h2 { color: #1a1a2e; margin-bottom: 8px; }
.card p { color: #666; line-height: 1.6; }
.card:hover { box-shadow: 0 8px 24px rgba(0,0,0,0.1); }
.card .badge { background: #667eea; color: white; }
/* With native nesting — organized! */
.card {
background: white;
border-radius: 12px;
padding: 24px;
h2 {
color: #1a1a2e;
margin-bottom: 8px;
}
p {
color: #666;
line-height: 1.6;
}
&:hover {
box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}
.badge {
background: #667eea;
color: white;
}
@media (min-width: 768px) {
padding: 32px;
}
}Tip
Native CSS nesting + CSS variables + @layer together replace 90% of what Sass was used for. For new projects in 2024+, consider starting with vanilla CSS before reaching for a preprocessor — you might not need one.
The cascade determines which style wins when multiple rules conflict
Common Mistake
Nesting too deeply (4+ levels). Both Sass and native nesting allow deep nesting, but it creates overly specific selectors and hard-to-read code. Keep nesting to 2-3 levels maximum. If you need deeper, restructure your HTML.
Practice Task
Convert flat CSS to nested: (1) Take a .card with separate rules for .card h2, .card p, .card:hover and nest them inside .card { }, (2) Add a @media query nested inside the card, (3) Use & for pseudo-classes like &:hover and &::after.
Quick Quiz
Key Takeaways
- Native CSS nesting is here — no preprocessor needed.
- & represents the parent — .card { & h2 { color: red; } } = .card h2 { color: red; }
- Implicit & — .card { h2 { } } works too, & is optional for descendant selectors
- & for pseudo-classes — .btn { &:hover { } } = .btn:hover { }