Sub topic 2
The & nesting selector
This chapter explains what the & nesting selector is and how browsers resolve it. It assumes you can read class, type, attribute, and pseudo-class selectors, and that you know the descendant, child, and sibling combinators. You should also know the basic cascade and specificity rules. The previous chapter showed a rule written inside another rule. This one explains the symbol that makes nesting precise.
What & stands for
Inside a nested rule, & is a placeholder for the parent rule's selector. Take the following rule:
.card {
padding: 1rem;
& .title {
font-weight: 600;
}
}The nested selector & .title means "a .title that is a descendant of whatever the parent selects". The parent here is .card, so the rule matches the same elements as the flat rule .card .title.
& does not paste text into your selector. The browser treats it as a reference to the parent selector as a whole. The specification describes it as behaving like :is() wrapped around the parent. Several behaviors in this chapter follow from that.
Reading nested selectors as flat selectors
The fastest way to check a nested rule is to rewrite it as a flat rule by replacing & with the parent selector. The table shows each rewrite for a parent of .card.
| Nested selector | Flat equivalent | Matches |
|---|---|---|
| `& .title` | `.card .title` | Any `.title` inside a `.card` |
| `& > p` | `.card > p` | A `p` that is a direct child of `.card` |
| `&:hover` | `.card:hover` | A `.card` under the pointer |
| `&.active` | `.card.active` | A `.card` that also has the class `active` |
| `.dark &` | `.dark .card` | A `.card` inside a `.dark` ancestor |
| `& + &` | `.card + .card` | A `.card` directly after another `.card` |
| `:not(&)` | `:not(.card)` | Any element that is not a `.card` |
Later chapters cover the compound, ancestor, and combinator forms in detail. For now, notice one thing in the table. Where you put & determines how the nested selector relates to the parent. At the start, as in & .title, the parent is on the left. At the end, as in .dark &, the parent is on the right and the other selector describes its context.
How the browser resolves &
A nested rule is parsed as part of its parent. When the browser builds the selector it uses these steps:
- It takes the parent rule's selector, which may be a list.
- It finds each
&in the nested selector and substitutes the parent selector, wrapped as if by:is(). - If the nested selector has no
&, it treats the selector as if it began with&(an&and a descendant combinator). This is the relaxed syntax, and the next chapter covers it. - It matches the resulting selector against the document like any other selector.
Because the replacement is a whole selector and not text, the result stays correct when the parent is complex. Here is a parent that is a selector list:
.error, .warning {
& .icon {
width: 1.25rem;
}
}This resolves to :is(.error, .warning) .icon. A plain text substitution would give .error, .warning .icon, and that would style every .error element, not just icons. The :is() behavior prevents that mistake.
A complete example
The following page uses & in four ways: a descendant, a state, a modifier class, and an ancestor context. You can save it as one HTML file and open it in a current browser.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Nesting selector demo</title>
<style>
.card {
padding: 1rem;
border: 1px solid #ccc;
background: white;
& .title {
margin: 0 0 0.5rem;
font-weight: 600;
}
&:hover {
border-color: #666;
}
&.featured {
border-color: gold;
border-width: 3px;
}
.dark-theme & {
background: #222;
color: #eee;
}
}
</style>
</head>
<body>
<div class="card"><h2 class="title">Plain card</h2></div>
<div class="card featured"><h2 class="title">Featured card</h2></div>
<div class="dark-theme">
<div class="card"><h2 class="title">Dark card</h2></div>
</div>
</body>
</html>The four nested rules resolve like this:
& .titlebecomes.card .title.&:hoverbecomes.card:hover.&.featuredbecomes.card.featured..dark-theme &becomes.dark-theme .card.
& is not string concatenation
If you have used Sass, you may have written &-title or &__title to build a longer class name. Native nesting does not allow this.
.card {
/* Invalid: the browser cannot append text to a selector */
&-title {
font-weight: 600;
}
}The reason is that & stands for a selector, not a string. Appending -title to :is(.card) has no meaning, so the browser drops the rule. The chapter on Sass differences returns to this. If you want the class .card-title, write it out:
.card {
& .card-title {
font-weight: 600;
}
}A related limit applies to type selectors. A type selector must come first in a compound selector, so &div is invalid. div& is valid and means "a div that is also a .card".
Using & more than once
A nested selector may contain & several times. Each one stands for the full parent selector.
.item {
& + & {
margin-top: 0.5rem;
}
& & {
opacity: 0.8;
}
}& + &resolves to:is(.item) + :is(.item). It matches an.itemthat directly follows another.item, which gives you spacing between siblings with no extra class.& &resolves to:is(.item) :is(.item). It matches an.itemnested somewhere inside another.item.
With a single simple parent like .item, this looks the same as repeating .item. The two differ when the parent is a list or a complex selector, because & repeats the whole parent each time.
Specificity of &
The :is() model also decides specificity. The specificity of & is the specificity of the most specific selector in the parent list. The nested selector's own parts are added to that value.
#main, .note {
& p {
color: red;
}
}This behaves like :is(#main, .note) p. The #main item is the most specific, so & contributes an ID. The specificity of the whole selector is (1,0,1): one ID plus one type selector.
This holds even for elements that match only through .note. A <p> inside <div class="note"> is styled by a rule with (1,0,1) specificity, not (0,1,1). Mixing selectors of different specificity in one parent list can therefore make nested rules win cascade conflicts you did not expect.
Where the parent is a single selector, the result is easy to predict.
| Parent | Nested | Specificity |
|---|---|---|
| `.card` | `& .title` | (0,2,0) |
| `.card` | `&:hover` | (0,2,0) |
| `.card` | `&.featured` | (0,2,0) |
| `#app` | `& .title` | (1,1,0) |
| `.card` | `p` | (0,1,1) |
The last row has no &. It is read as & p, so the parent's .card still counts.
Where & can and cannot match
Three edge cases catch people out.
Pseudo-elements
& cannot represent a pseudo-element. If the parent selector ends in ::before or ::after, a nested selector that uses & as a parent never matches.
.quote::before {
content: "“";
/* Never matches: & would have to stand for a pseudo-element */
& span {
color: red;
}
}Writing &::before in a nested rule is fine. The pseudo-element goes on the nested selector, not the parent. For example, .quote { &::before { content: "“"; } } works.
Invalid selectors in a list
When a nested rule has a selector list, one invalid selector makes the whole rule invalid. Normal top-level rules behave the same way. It is different from :is(), which ignores invalid items inside it. If a nested list stops working, look for a single bad entry.
Use outside a nested rule
At the top level of a stylesheet, & has no parent rule. It then matches the same element as :scope, which in a normal document is the root html element. You rarely need this, but it explains why a stray & outside a rule does not cause an error.
Summary of the working model
&is a reference to the parent selector as a whole, not copied text.- Placement of
&sets the relationship. At the start it describes the parent's descendants and states. At the end it describes the parent's ancestors. - A parent that is a list is wrapped like
:is(), so each nested selector applies to every item in the list. - Specificity comes from the most specific item in the parent list.
- Suffix building such as
&-title,&div, and pseudo-element parents do not work.
Exercise
A stylesheet contains this rule. (1) Write the flat selector the browser matches for the nested rule. (2) Give its specificity as (IDs, classes, types). (3) Would a <p> inside <div class="note"> be styled by a rule with that specificity?
#page, .note {
& p {
margin: 0;
}
}
Show answer
(1) :is(#page, .note) p. (2) (1,0,1), because :is() takes the specificity of its most specific item, #page, and p adds one type selector. (3) Yes. The p is matched through .note, but the rule still carries the specificity (1,0,1), not (0,1,1).
Exercise
Rewrite this Sass-style rule as valid native CSS so it styles an element with the class "button-primary" when it is hovered, without using string concatenation. Then explain in one sentence why the original does not work. .button { &-primary:hover { background: navy; } }
Show answer
Valid version: .button-primary:hover { background: navy; } as a separate rule, or nested as .button { & + .x {} } is not needed. The simplest correct nested form is .button { &.button-primary:hover { background: navy; } } if the element has both classes, or a separate flat rule if it only has button-primary. The original fails because & stands for the whole selector :is(.button), so the browser cannot append "-primary" to it, and the rule is dropped.