Nesting and Scope
๐ Covered in this chapter:
Native Nesting ยท Nested Selectors ยท Nested @media ยท @scope ยท Scope Boundaries ยท Limitations ยท Sass Comparison ยท Migration ยท Browser Support
Welcome to Chapter 44: Nesting and Scope โ part of the CSS Complete Roadmap. This lesson covers all subtopics with clear explanations, code examples, and best practices used in professional web development.
๐ What You Will Learn
- Native CSS nesting syntax โ no preprocessor required
- Nested @media queries inside selectors
- @scope rule for limiting selector reach
- Nesting limitations and anti-patterns
- Migrating from Sass/Less to native CSS
๐ก Why This Matters
CSS nesting landed in all major browsers (2023-2024). Developers can finally write organized, component-scoped CSS without Sass. @scope adds another layer โ explicit boundaries preventing styles from leaking outside a subtree.
1Native CSS Nesting Syntax
CSS โ Nested Componentโถ Try in Editor
.card {
padding: 24px;
border-radius: 12px;
background: #fff;
& .card__title {
font-size: 1.25rem;
font-weight: 700;
}
&:hover {
box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}
&.card--featured {
border: 2px solid #2563eb;
}
@media (max-width: 768px) {
padding: 16px;
}
}
/* Compiles equivalent to: .card .card__title, .card:hover, etc. */
& rule: & required when nesting modifier (&--featured) or pseudo-class (&:hover). Element nesting (.card { .title {} }) works without & in modern browsers.
2@scope โ Limiting Style Reach
CSS โ @scopeโถ Try in Editor
@scope (.article) {
h2 { color: #2563eb; font-size: 1.5rem; }
p { line-height: 1.7; color: #374151; }
a { color: #7c3aed; }
}
/* h2, p, a styles ONLY apply inside .article โ not globally */
@scope prevents global h2 styles from affecting navbar headings. Explicit boundary vs BEM naming convention.
3Nesting Limitations & Sass Migration
| Feature | Sass | Native CSS |
|---|---|---|
| Nesting | โ Full | โ Modern browsers |
| Variables | $var | --custom-properties (better!) |
| Mixins | โ @mixin | โ Use @layer or utilities |
| Functions | โ darken() | color-mix(), calc() |
| @scope | โ | โ Native only |
โ ๏ธ Common Mistakes
- Nesting more than 3 levels deep โ specificity explosion
- Nesting without & for compound selectors โ can fail in edge cases
- Using nesting to mirror HTML structure instead of component thinking
- Global element selectors inside nested blocks โ still global within scope
โ
Quick Recap
- Native CSS nesting: use & for modifiers and pseudo-classes
- Nested @media inside selectors โ cleaner responsive code
- @scope limits style reach to a subtree
- CSS custom properties replace Sass variables
- Avoid deep nesting โ max 2-3 levels for maintainability