Nesting in Sass and SCSS
Sass nesting allows you to write selectors inside other selectors, unlike plain CSS, and mirrors the HTML structure. This reduces repetition and makes your styles easier to read and maintain.
In this tutorial, you will learn what nesting is, how to implement nested structure in both SCSS and indented Sass, practical patterns to use, and common pitfalls to avoid.
What is Nesting in Sass?
Nesting is a way to place child selectors inside parent selectors. It mirrors the DOM and keeps related rules together.
- Reflects HTML structure
- Reduces repeated selector text
- Improves readability
- Helps organize styles for components
- Makes maintenance easier by grouping related rules
- Supports pseudo-classes and modifiers cleanly
- No strict limit on nesting depth, but keep it practical
Basic Nesting Example
.container { .card { padding: 16px; border: 1px solid #ddd; } }
.container .card padding: 16px border: 1px solid #ddd
How Nesting Works in Sass?
Sass supports writing selectors inside other selectors and using the parent selector ampersand & to refer to the current selector. This helps manage pseudo-classes, modifiers, and keeps related rules grouped.
- Write child selectors directly inside parent selectors
- Reference the parent with & when needed
- Nest multiple levels for structure, but stay concise
- Combine classes and elements efficiently
- Group related rules to reduce repetition
Nesting With Parent Selector
.button { background: blue; &:hover { background: linear-gradient(to right, blue, #333); } .icon { margin-right: 8px; } }
.button { background: blue; } .button:hover { background: linear-gradient(to right, blue, #333); } .button .icon { margin-right: 8px; }
Best Practices for Sass Nesting
Sass nesting makes CSS more organized, but excessive depth can create hard-to-maintain selectors. Focus on small, clear blocks and practical use of the ampersand.
- Keep nesting shallow, ideally 2–3 levels
- Choose clear, descriptive class names over long tag chains
- Use interpolation to generate dynamic class or ID names within nested selectors
- Use & for modifiers instead of deep descendant selectors
Limit Nesting Depth
.card { header { /* ok */ } .content { section { article { /* avoid deeper nesting */ } } p { /* ok */ } } }
Common Mistakes to Avoid
Over nesting creates high specificity and large compiled CSS. Avoid relying on long selector chains or deeply nested style rules in Sass stylesheets.
- Avoid chaining many elements
- Do not create selectors tied to deep DOM structure
- Use placeholders or utilities for reuse
Over-nesting Example
.site { main { article { section { div { p { /* avoid deeper nesting */ } } } } } }
.site main article section div p { /* avoid deeper nesting */ }
Use nesting to group related rules, reduce repetition, and maintain clear class structure for both Sass and compiled CSS.