Sub topic 5
Nesting rules and the & selector
Nesting lets you write a child rule inside its parent rule. Sass expands it into ordinary CSS selectors at compile time. This chapter covers how selectors are combined, the ways to use the parent selector &, how nested at-rules behave, and the mistakes that produce bloated or surprising CSS.
You should already know CSS selectors, combinators, specificity and media queries. You should also be able to compile a file with sass src/styles.scss dist/styles.css, as covered earlier. The examples use SCSS syntax, and the compiled output shown is Dart Sass's default expanded style.
How nesting expands
A nested rule is joined to its parent with a descendant combinator (a space) by default.
.nav {
margin: 0;
ul {
list-style: none;
}
a {
color: #3366cc;
}
}.nav {
margin: 0;
}
.nav ul {
list-style: none;
}
.nav a {
color: #3366cc;
}Three points follow from this output:
- The parent keeps its own declarations as a separate rule.
- Each child becomes its own flat rule with the full selector written out.
- The nesting exists only in the source. The CSS contains no nesting.
You can start a nested selector with a combinator to change how it attaches. Leading >, + and ~ are all allowed.
.menu {
> li {
display: inline-block;
}
+ .menu {
margin-top: 1rem;
}
}.menu > li {
display: inline-block;
}
.menu + .menu {
margin-top: 1rem;
}The parent selector &
The & character stands for the complete selector of the enclosing rule. You use it whenever the child should attach to the parent without a space.
$primary: #3366cc;
$radius: 4px;
.card {
padding: 1rem;
border: 1px solid $primary;
border-radius: $radius;
&:hover {
background: rgba($primary, 0.1);
}
&__title {
font-weight: 700;
}
}.card {
padding: 1rem;
border: 1px solid #3366cc;
border-radius: 4px;
}
.card:hover {
background: rgba(51, 102, 204, 0.1);
}
.card__title {
font-weight: 700;
}Without &, :hover would be written as .card :hover. That selector matches hovered descendants, not the card itself.
Where & can appear
& is a placeholder that Sass replaces textually, so it works in several positions:
| Position | Source inside `.button` | Result |
|---|---|---|
| Pseudo-class | `&:focus` | `.button:focus` |
| Compound class | `&.is-active` | `.button.is-active` |
| Suffix | `&--large` | `.button--large` |
| Repeated | `& + &` | `.button + .button` |
| Context before | `.no-js &` | `.no-js .button` |
.button {
padding: 0.5rem 1rem;
&.is-active {
font-weight: 700;
}
& + & {
margin-left: 0.5rem;
}
.no-js & {
display: none;
}
}The last form is the most useful one beginners miss. Placing & after other selectors lets a child rule depend on an ancestor, such as a theme class or a feature-detection class on <html>. You write the rule next to the component instead of in a separate "overrides" section.
& with a suffix, such as &__title, is only valid at the start of a compound selector. You can't write .x &__title. Sass reports an error because the result would be ambiguous.
Selector lists
When the parent or the child is a comma-separated list, Sass produces every combination.
.alert,
.notice {
padding: 1rem;
&-title {
font-weight: 700;
}
.icon & {
color: #cc3333;
}
}.alert,
.notice {
padding: 1rem;
}
.alert-title,
.notice-title {
font-weight: 700;
}
.icon .alert,
.icon .notice {
color: #cc3333;
}Lists multiply quickly. A parent with three selectors and a child with four produces twelve compiled selectors. This is useful, but watch the output size when you nest lists inside lists.
The next diagram shows how one nested source rule becomes several flat selectors.
Nesting at-rules
You can nest @media and @supports inside a rule. Sass moves the at-rule to the top level and wraps the selector inside it.
.sidebar {
width: 100%;
@media (min-width: 48rem) {
width: 20rem;
}
}.sidebar {
width: 100%;
}
@media (min-width: 48rem) {
.sidebar {
width: 20rem;
}
}This keeps each component's breakpoints beside its base styles. Sass does not merge identical media queries across the file. Ten components with the same breakpoint produce ten @media blocks. That is valid CSS, but it is larger than a hand-grouped file, and gzip reduces most of the cost.
Nested properties and @at-root
Properties that share a prefix can be nested under it. The prefix needs a colon, and the block follows.
.heading {
font: {
family: Georgia, serif;
size: 1.5rem;
weight: 700;
}
}.heading {
font-family: Georgia, serif;
font-size: 1.5rem;
font-weight: 700;
}Use @at-root when a nested rule should be emitted without the parent selector in front of it:
.card {
color: #222;
@at-root .card-legend {
color: #666;
}
}.card {
color: #222;
}
.card-legend {
color: #666;
}Common errors
Nesting too deeply
Every level adds to the selector, and so to its specificity.
.page {
.content {
.article {
.body {
p {
margin: 0;
}
}
}
}
}This compiles to .page .content .article .body p. That selector has four classes and one element. It is hard to override later and breaks when the markup changes. A common rule of thumb is to nest no more than three levels deep. Prefer a flat class such as .article__body over a long chain of descendants.
Declarations after nested rules
.panel {
color: #222;
&:hover {
color: #000;
}
border: 1px solid #ccc;
}Using & where it can't go
& is only valid inside a nested rule. At the top level of a file it is an error. A suffix like &-title only works at the start of a compound selector, as noted above.
Treating nesting as a naming tool only
Nesting &__title gives you BEM-style names without repeating the block name. It does not give you scoping. The output is still global CSS, and .card__title is matched anywhere it appears. Nesting changes how you write selectors, not how the browser applies them.
Working habits
- Write declarations first, then pseudo-classes and modifiers with
&, then child elements, then media queries. - Use
&suffixes for BEM elements and modifiers so you can rename a block in one place. - Use
.context &for ancestor-dependent styles instead of a second rule far from the component. - Compile and read the CSS now and then. If a selector surprises you, the compiled file shows what the browser receives.
Exercise
Write SCSS that compiles to the CSS below, using nesting and & only. You may not repeat the word "tab" more than once. .tab { padding: 0.5rem; } .tab.is-open { font-weight: 700; } .tab + .tab { margin-left: 0.25rem; } .dark .tab { color: #eee; }
Show answer
.tab { padding: 0.5rem; &.is-open { font-weight: 700; } & + & { margin-left: 0.25rem; } .dark & { color: #eee; } }
Exercise
What CSS selectors does this SCSS produce, and why might this pattern be a problem at scale? .a, .b { .c & { margin: 0; } }
Show answer
It produces ".c .a, .c .b". Sass combines the list with the context selector, so each list item gets the ".c " prefix. At scale, nested lists multiply: a parent list of n selectors and a child list of m selectors yield n times m selectors, which can inflate the output and make specificity harder to reason about.