Sub topic 6
Styling by ancestor context with & at the end
This chapter assumes you know how the & nesting selector works with child and compound selectors. It also assumes you can read descendant and child combinators and compare specificity values written as (ids, classes, types). Here you will learn to put & after other selectors, so a nested rule styles an element based on where it sits in the page.
The idea
Most nested rules describe what is inside the parent or what state the parent is in. Sometimes you need the reverse: "when this component is inside a dark theme, change it." Without nesting, you would write that rule far from the component, or repeat the component's selector.
Placing & after another selector gives the nested rule that context. The nested rule stays next to the component it changes.
.card {
padding: 1rem;
background: white;
color: #222;
.dark-theme & {
background: #222;
color: #eee;
}
}The browser replaces & with the parent selector. The nested rule above is equivalent to this:
.dark-theme .card {
background: #222;
color: #eee;
}The space between .dark-theme and & is a descendant combinator. The .card must be inside an element with the class dark-theme.
How the browser resolves it
The resolution is not text substitution. The browser treats & as if it were :is(parent), and the nested selector is matched against that. For a simple parent such as .card, the result looks the same as plain substitution. The difference shows up with complex parents and selector lists, covered below.
Ancestor patterns
You can put any selector before &. Each pattern below is written inside a .card rule.
| Nested selector | Resolves to | Meaning |
|---|---|---|
| `.dark-theme &` | `.dark-theme .card` | Card anywhere inside `.dark-theme` |
| `.sidebar > &` | `.sidebar > .card` | Card that is a direct child of `.sidebar` |
| `body.print &` | `body.print .card` | Card inside a `body` that has class `print` |
| `:root[data-theme="dark"] &` | `:root[data-theme="dark"] .card` | Card when the root element has a data attribute |
| `.grid:has(&)` | `.grid:has(.card)` | A `.grid` that contains a card |
| `:not(&)` | `:not(.card)` | Any element that is not a card |
Two points about the table.
- The
&can sit inside a functional pseudo-class such as:has()or:not(). In.grid:has(&), the rule styles the.grid, not the card. Check which element the selector's last compound selector targets. - You can use
&more than once.& + &becomes.card + .card, which styles a card that directly follows another card.
A complete example
This page switches themes by changing one class on a wrapper element. Save it and open it in a current browser to try it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ancestor context</title>
<style>
.card {
padding: 1rem;
margin: 1rem;
border: 1px solid #ccc;
background: white;
color: #222;
.title {
font-weight: 600;
}
.dark-theme & {
background: #222;
color: #eee;
border-color: #555;
.title {
color: gold;
}
}
}
</style>
</head>
<body>
<div class="card"><p class="title">Light card</p></div>
<div class="dark-theme">
<div class="card"><p class="title">Dark card</p></div>
</div>
</body>
</html>The inner .title rule is nested two levels deep. Inside .dark-theme &, the & for that inner rule stands for the whole .dark-theme .card. So the inner rule resolves to .dark-theme .card .title.
Complex parents and the :is() behavior
When the parent is more than one compound selector, & keeps it grouped. Consider this rule.
.nav {
a {
.dark-theme & {
color: #9cf;
}
}
}The innermost rule resolves to .dark-theme :is(.nav a). It does not become .dark-theme .nav a. The two forms often match the same elements, but they are not identical.
.page .card {
.dark-theme & {
background: #222;
}
}This resolves to .dark-theme :is(.page .card). It matches a .card that has both a .page ancestor and a .dark-theme ancestor. The order of those ancestors does not matter. If the .dark-theme element sits inside .page, the rule still applies. Sass would produce .dark-theme .page .card, which requires .dark-theme to be the outermost ancestor.
Selector lists as parents
If the parent is a selector list, & stands for :is() over the whole list.
.card, .panel {
.dark-theme & {
background: #222;
}
}This resolves to .dark-theme :is(.card, .panel), which matches both .dark-theme .card and .dark-theme .panel. A Sass author would expect the same result here. The difference appears in specificity.
Specificity
The specificity of a nested selector is the specificity of everything written in it, with & counted as :is(parent). The :is() function takes the specificity of its most specific argument.
For .dark-theme & inside .card:
.dark-themecontributes (0,1,0).&is:is(.card), which contributes (0,1,0).- The total is (0,2,0), the same as
.dark-theme .card.
For the list case, take this rule.
#main, .note {
.dark-theme & {
color: white;
}
}The & becomes :is(#main, .note) and counts as (1,0,0), because the id is the most specific item in the list. The total is (1,1,0). That applies even when the rule matches an element only through .note. A .note element therefore gets a specificity it would not have in a hand-written .dark-theme .note rule, which is (0,2,0).
For .dark-theme :is(.nav a) from the earlier example, & counts (0,1,1). The total is (0,2,1).
Interaction with source order
A context rule usually has higher specificity than the base rule, so it wins no matter where it sits. A tie is the case that can surprise you.
.card {
border-color: #ccc;
&:hover {
border-color: #666;
}
.dark-theme & {
border-color: #444;
}
}Both .card:hover and .dark-theme .card have specificity (0,2,0). The later rule wins when both match. In this example, a hovered dark card shows #444, and the hover color is lost. To fix it, write the dark rule before the hover rule, or add a dark hover rule.
.card {
border-color: #ccc;
.dark-theme & {
border-color: #444;
&:hover {
border-color: #aaa;
}
}
&:hover {
border-color: #666;
}
}The dark hover rule resolves to .dark-theme .card:hover, with specificity (0,3,0). It beats the plain hover rule.
Common errors
- Forgetting
&. Writing.dark-theme { background: #222; }inside.cardstyles a.dark-themeelement inside the card. It does not style the card. Without&, the nested selector is relative to the parent and is a descendant of it. - Expecting Sass-style concatenation.
.dark-theme &-titleis invalid. Native nesting does not append text to the parent selector. - Assuming ancestor order from a complex parent. As shown above,
.dark-theme &inside.page .cardmatches the ancestors in either order. - Targeting the wrong element. In
.grid:has(&), the styled element is the.grid. Declarations inside that rule apply to the grid, not to the card. - Unexpected specificity from lists. A parent list containing an id raises the weight of every nested context rule.
When to use this pattern
Ancestor context is the right tool for theme switches, layout-dependent variants such as .sidebar > &, and print or state classes on body or :root. It keeps a component's variants in one place.
It is a poor fit when the context changes many components at once. In a theme switch, setting custom properties on .dark-theme once is usually shorter. Components then read those variables without needing a nested rule each.
Exercise
Inside a .btn rule you write .toolbar > & { margin: 0; }. What selector does the browser match, and what is its specificity?
Show answer
It matches .toolbar > .btn, a .btn that is a direct child of .toolbar. The specificity is (0,2,0): one class for .toolbar and one for &, which counts as :is(.btn).
Exercise
Given .a, #b { .dark & { color: red; } }, what is the specificity of the nested selector, and why is it higher than the .a branch alone would suggest?
Show answer
It is (1,1,0). The & becomes :is(.a, #b), and :is() takes the specificity of its most specific argument, which is #b at (1,0,0). The .dark class adds (0,1,0). The rule gets this weight even for an element matched only through .a.
Exercise
You have .card { .dark-theme & { border-color: #444; } &:hover { border-color: #666; } }. A hovered card inside .dark-theme shows #666. Explain why, and give one change that makes the dark theme win.
Show answer
Both selectors have specificity (0,2,0), so source order decides, and the later &:hover rule wins. Moving the .dark-theme & rule after &:hover would make the dark border win on hover, though it would hide the hover effect. A better change is to nest &:hover inside the dark rule, which gives .dark-theme .card:hover at (0,3,0), and set a dark hover color there.