SCSS by Example: Nesting
Mirroring HTML hierarchy in stylesheets with this code example showing nested selector syntax, parent selector reference using ampersand, pseudo-class nesting, and how nested rules compile to descendant selectors in CSS.
Code
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
display: inline-block;
}
a {
display: block;
padding: 6px 12px;
text-decoration: none;
// Parent selector reference (&)
&:hover {
background-color: #eee;
}
&.active {
font-weight: bold;
}
}
}Explanation
Nesting in SCSS allows selectors to be written inside one another, creating a visual hierarchy that mirrors the HTML structure. When compiled, nested selectors are transformed into descendant selectors in the final CSS. For example, ul nested inside nav compiles to nav ul. This feature improves code organization and readability by grouping related styles together and reducing selector repetition.
The ampersand & symbol is a special character that references the parent selector in nested contexts. It enables several important patterns:
- Pseudo-classes like
&:hover,&:focus,&:activecompile toselector:hover - Pseudo-elements like
&::before,&::afterfor generated content - Modifier classes like
&.activecompile toselector.active - BEM notation like
&__elementand&--modifierfor component architecture - Suffix patterns like
&-suffixfor creating related class names
While nesting provides organizational benefits, excessive nesting depth can generate overly specific selectors that are difficult to override and can increase CSS file size. The compiled output specificity increases with each nesting level, potentially creating maintenance challenges. The ampersand can also be placed after selectors for reverse nesting patterns, useful for contextual styling where a parent class affects child appearance.
Code Breakdown
ul { ... } nested in nav compiles to nav ul { ... }.&:hover references parent selector, compiles to nav a:hover.&.active combines parent with class, compiles to nav a.active.nav a descendant selector with modifiers.
