Sass Nesting

Sass Nesting – Complete Practical Guide
Sass nesting allows you to write CSS selectors inside other selectors, mirroring your HTML structure and making styles more readable.
Think of It as organizing related CSS together.
1. What Is Sass Nesting?
In plain CSS, selectors must be written repeatedly.
In Sass, you can nest child selectors inside parent selectors.
CSS (without nesting)
2. Basic Nesting Syntax
- Same output
- Better readability
- Too much nesting (we’ll fix this later)
3. How Sass Nesting Compiles
The nested Sass above compiles to:
Sass simply combines selectors.
4. Nesting Pseudo-Classes & Pseudo-Elements
Use & to reference the parent selector.
4.1 :hover, :focus
4.2 ::before and ::after
5. The Parent Selector & (Very Important)
& represents the current selector.
Modifier Pattern (BEM-style)
Compiles to:
6. Nesting Media Queries
Keeps responsive rules close to the component.
7. Nesting with @supports
Clean progressive enhancement inside components.
8. Property Nesting (Optional)
It allows property nesting.
Compiles to:
Use sparingly.
9. Common Nesting Mistakes
- Over-nesting (deep selectors)
- Mimicking full HTML structure
- Nesting utility classes
- Creating high specificity
- Hard-to-override selectors
Bad example:
10. Best Practice: 3-Level Rule
Never nest more than 2–3 levels deep
Good example:
Flat, predictable CSS.
11. Sass Nesting vs CSS Nesting
| Feature | Sass Nesting | CSS Nesting |
|---|---|---|
| Support | All Sass projects | Limited browsers |
| Compile step | Yes | No |
| Power | Advanced (&, logic) | Basic |
| Production ready | Yes | Partial |
12. Accessibility & Performance
Nesting does not affect DOM
Screen readers unaffected
Deep selectors increase CSS specificity
Shallow nesting = faster overrides
13. Interview-Level Questions
Q: What is Sass nesting?
Writing selectors inside other selectors.
Q: What does & represent?
The parent selector.
Q: Biggest danger of nesting?
Over-specific and hard-to-maintain CSS.
Q: Recommended nesting depth?
2–3 levels max.
Best Practices Summary
Keep nesting shallow
Use
&for modifiers and statesAvoid nesting full HTML trees
Combine with BEM naming
Prefer readability over cleverness
Final Summary
It improves readability
Mirrors component structure
&enables powerful selector controlOver-nesting is harmful
Clean nesting = scalable CSS
