What is nesting in Sass and its pitfall?
ergonomic Sass authoring and its risks.
nesting writes child rules inside parents mirroring structure, but deep nesting generates long descendant selectors with high specificity.
WHAT THIS TESTS This checks both that you can use Sass nesting and that you understand its most common abuse. The signal of maturity is naming the specificity and coupling problems, not just describing the syntax.
A GOOD ANSWER COVERS Nesting in Sass lets you write child selectors inside the curly braces of a parent rule, so the source structure mirrors the DOM and related styles sit together. The ampersand refers to the parent selector, which is powerful for states and BEM modifiers, for example writing the parent then &:hover or &--primary. The pitfall is over-nesting. Each level deepens the compiled descendant selector, so three or four levels produce a long chain that has high specificity, is hard to override, and is tightly coupled to a specific HTML structure that breaks if the markup changes. To avoid it: keep nesting shallow, often no more than two or three levels; nest for states and pseudo-classes rather than to mirror every wrapper; and combine the ampersand with BEM so you emit flat single-class selectors like .card__title instead of long descendant chains.
COMMON WRONG ANSWERS Saying nesting only improves things with no downside. Nesting deeply to mirror the whole DOM, creating specificity and coupling problems. Forgetting the ampersand's role for states and modifiers. Confusing Sass nesting with native CSS nesting differences.
LIKELY FOLLOW-UPS What does the ampersand do, and how does it help BEM? How deep is too deep? How does over-nesting hurt overrides? How does native CSS nesting compare with Sass nesting?
ONE CONCRETE EXAMPLE Using the ampersand, you write a card block and nest &:hover and &--primary so the compiled output is flat low-specificity selectors like .card:hover and .card--primary. Contrast that with nesting a list inside an item inside a body inside the card, which compiles to .card .card__body .list .list__item, a long, brittle, high-specificity selector you should flatten using BEM names instead.
Read the original → sass-lang.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.