1. Introduction
This section is not normative.
This module describes support for nesting a style rule within another style rule, allowing the inner rule’s selector to reference the elements matched by the outer rule. This feature allows related styles to be aggregated into a single structure within the CSS document, improving readability and maintainability.
1.1. Module Interactions
This module introduces new parser rules that extend the [CSS21] parser model. It introduces selectors that extend the [SELECTORS-4] module. It extends and modifies some IDL and algorithms defined in the [CSSOM-1] module.
1.2. Values
This specification does not define any new properties or values.
1.3. Motivation
The CSS for even moderately complicated web pages often include lots of duplication for the purpose of styling related content. For example, here is a portion of the CSS markup for one version of the [CSS-COLOR-3] module:
table.colortable td{ text-align : center; } table.colortable td.c{ text-transform : uppercase; } table.colortable td:first-child, table.colortable td:first-child+td{ border : 1 px solid black; } table.colortable th{ text-align : center; background : black; color : white; }
Nesting allows the grouping of related style rules, like this:
table.colortable{ & td{ text-align : center; &.c{ text-transform : uppercase} &:first-child, &:first-child + td{ border : 1 px solid black} } & th{ text-align : center; background : black; color : white; } }
Besides removing duplication, the grouping of related rules improves the readability and maintainability of the resulting CSS.
2. Nesting Style Rules
Style rules can be nested inside of other styles rules.
These nested style rules act exactly like ordinary style rules—
A nested style rule is exactly like a normal style rule, except that it can use can use relative selectors, which are implicitly relative to the elements matched by the parent rule.
.foo{ color : red; a{ color : blue; } }
is valid, and equivalent to:
.foo{ color : red; } .foo a{ color : blue; }
The nested rule can also use the nesting selector to directly refer to the parent rule’s matched elements, or use relative selector syntax to specify relationships other than "descendant".
.foo{ color : red; &:hover{ color : blue; } } /* equivalent to: */ .foo{ color : red; } .foo:hover{ color : blue; }
.foo{ color : red; + .bar{ color : blue; } } /* equivalent to: */ .foo{ color : red; } .foo + .bar{ color : blue; }
2.1. Syntax
The contents of style rules now accepts nested style rules and at-rules, in addition to the existing declarations.
Nested style rules differ from non-nested rules in the following ways:
-
A nested style rule accepts a <relative-selector-list> as its prelude (rather than just a <selector-list>). Any relative selectors are relative to the elements represented by the nesting selector.
-
If a selector in the <relative-selector-list> does not start with a combinator but does contain the nesting selector, it is interpreted as a non-relative selector.
The precise details of how nested style rules are parsed are defined in [CSS-SYNTAX-3].
An invalid nested style rule is ignored, along with its contents, but does not invalidate its parent rule.
/* & can be used on its own */ .foo{ color : blue; & > .bar{ color : red; } > .baz{ color : green; } } /* equivalent to .foo { color: blue; } .foo > .bar { color: red; } .foo > .baz { color: green; } */ /* or in a compound selector, refining the parent’s selector */ .foo{ color : blue; &.bar{ color : red; } } /* equivalent to .foo { color: blue; } .foo.bar { color: red; } */ /* multiple selectors in the list are all relative to the parent */ .foo, .bar{ color : blue; + .baz, &.qux{ color : red; } } /* equivalent to .foo, .bar { color: blue; } :is(.foo, .bar) + .baz, :is(.foo, .bar).qux { color: red; } */ /* & can be used multiple times in a single selector */ .foo{ color : blue; & .bar & .baz & .qux{ color : red; } } /* equivalent to .foo { color: blue; } .foo .bar .foo .baz .foo .qux { color: red; } */ /* & doesn’t have to be at the beginning of the selector */ .foo{ color : red; .parent &{ color : blue; } } /* equivalent to .foo { color: red; } .parent .foo { color: blue; } */ .foo{ color : red; :not ( &) { color : blue; } } /* equivalent to .foo { color: red; } :not(.foo) { color: blue; } */ /* But if you use a relative selector , an initial & is implied automatically */ .foo{ color : red; + .bar + &{ color : blue; } } /* equivalent to .foo { color: red; } .foo + .bar + .foo { color: blue; } */ /* Somewhat silly, but & can be used all on its own, as well. */ .foo{ color : blue; &{ padding : 2 ch ; } } /* equivalent to .foo { color: blue; } .foo { padding: 2ch; } // or .foo { color: blue; padding: 2ch; } */ /* Again, silly, but can even be doubled up. */ .foo{ color : blue; &&{ padding : 2 ch ; } } /* equivalent to .foo { color: blue; } .foo.foo { padding: 2ch; } */ /* The parent selector can be arbitrarily complicated */ .error, #404{ &:hover > .baz{ color : red; } } /* equivalent to :is(.error, #404):hover > .baz { color: red; } */ .ancestor .el{ .other-ancestor &{ color : red; } } /* equivalent to .other-ancestor :is(.ancestor .el) { color: red; } /* As can the nested selector */ .foo{ &:is ( .bar, &.baz) { color : red; } } /* equivalent to .foo :is(.bar, .foo.baz) { color: red; } */ /* Multiple levels of nesting "stack up" the selectors */ figure{ margin : 0 ; > figcaption{ background : hsl ( 0 0 % 0 % /50 % ); > p{ font-size : .9 rem ; } } } /* equivalent to figure { margin: 0; } figure > figcaption { background: hsl(0 0% 0% / 50%); } figure > figcaption > p { font-size: .9rem; } */ /* Example usage with Cascade Layers */ @layer base{ html{ block-size : 100 % ; body{ min-block-size : 100 % ; } } } /* equivalent to @layer base { html { block-size: 100%; } html body { min-block-size: 100%; } } */ /* Example nesting Cascade Layers */ @layer base{ html{ block-size : 100 % ; @layer support{ body{ min-block-size : 100 % ; } } } } /* equivalent to @layer base { html { block-size: 100%; } } @layer base.support { html body { min-block-size: 100%; } } */ /* Example usage with Scoping */ @scope ( .card) to( > header) { :scope{ inline-size : 40 ch ; aspect-ratio : 3 /4 ; > header{ border-block-end : 1 px solid white; } } } /* equivalent to @scope (.card) to (> header) { :scope { inline-size: 40ch; aspect-ratio: 3/4; } :scope > header { border-block-end: 1px solid white; } } */ /* Example nesting Scoping */ .card{ inline-size : 40 ch ; aspect-ratio : 3 /4 ; @scope ( &) to( > header > *) { :scope > header{ border-block-end : 1 px solid white; } } } /* equivalent to .card { inline-size: 40ch; aspect-ratio: 3/4; } @scope (.card) to (> header > *) { :scope > header { border-block-end: 1px solid white; } } */
For example, if one component uses the class .foo, and a nested component uses .fooBar, you could write this in Sass as:
.foo{ color : blue; &Bar{ color : red; } } /* In Sass, this is equivalent to .foo { color: blue; } .fooBar { color: red; } */
This is not allowed in CSS, as nesting is not a syntax transformation, but rather matches on the actual elements the parent selector matches.
It is also true that the selector &Bar is invalid in CSS in the first place, as the Bar part is a type selector, which must come first in the compound selector. (That is, it must be written as Bar&.) So, luckily, there is no overlap between CSS Nesting and the preprocessor syntax.
Note: This is phrased in this explicit manner so as to catch cases like :is(:unknown(&), .bar), where an unknown selector (which, being unknown, we have no way of knowing whether the argument is meant to be parsed as a selector or not) is the only part of the selector that contains an &. As that might be a perfectly valid selector that’s only supported by newer browsers, and we don’t want parsing to be dependent on unrelated versioning issues, we treat it as still containing the nesting selector.
If a <forgiving-selector-list> has an item that contains the nesting selector but is invalid,
that item is preserved exactly as-is
rather than being discarded.
(This does not change the matching behavior of the selector—
The preceding paragraph needs to move to Selectors when we move & itself to Selectors; I’m monkey-patching for convenience here.
2.2. Nesting Other At-Rules
In addition to nested style rules, this specification allows nested group rules inside of style rules: any at-rule whose body contains style rules can be nested inside of a style rule as well.
When nested in this way, the contents of a nested group rule's block are parsed as <block-contents> rather than <rule-list>:
-
Style rules are nested style rules, with their nesting selector taking its definition from the nearest ancestor style rule.
-
Properties can be directly used, acting as if they were nested in a
& {...}
block.
-
all the conditional group rules (@media, @supports)
The meanings and behavior of such nested group rules is otherwise unchanged, unless otherwise specified.
/* Properties can be directly used */ .foo{ display : grid; @media ( orientation: landscape) { grid-auto-flow : column; } } /* equivalent to .foo { display: grid; @media (orientation: landscape) { & { grid-auto-flow: column; } } } */ /* finally equivalent to .foo { display: grid; } @media (orientation: landscape) { .foo { grid-auto-flow: column; } } */ /* Conditionals can be further nested */ .foo{ display : grid; @media ( orientation: landscape) { grid-auto-flow : column; @media ( min-width >1024 px ) { max-inline-size : 1024 px ; } } } /* equivalent to .foo { display: grid; } @media (orientation: landscape) { .foo { grid-auto-flow: column; } } @media (orientation: landscape) and (min-width > 1024px) { .foo { max-inline-size: 1024px; } } */ /* Example nesting Cascade Layers */ html{ @layer base{ block-size : 100 % ; @layer support{ & body{ min-block-size : 100 % ; } } } } /* equivalent to @layer base { html { block-size: 100%; } } @layer base.support { html body { min-block-size: 100%; } } */ /* Example nesting Scoping */ .card{ inline-size : 40 ch ; aspect-ratio : 3 /4 ; @scope ( &) { :scope{ border : 1 px solid white; } } } /* equivalent to .card { inline-size: 40ch; aspect-ratio: 3/4; } @scope (.card) { :scope { border-block-end: 1px solid white; } } */
All directly-nested properties are treated
as if they were collected together, in order,
and nested in a nested style rule with the selector &,
and placed before all other child rules.
This includes in the OM.
(That is,
the cssRules
attribute
actually starts with this nested style rule,
containing all the directly-nested properties.)
For example, the earlier example:
.foo{ display : grid; @media ( orientation: landscape) { grid-auto-flow : column; } } /* equivalent to .foo { display: grid; @media (orientation: landscape) { & { grid-auto-flow: column; } } } */
is in fact exactly equivalent,
producing the exact same CSSOM structure.
The CSSMediaRule
object
will have a single CSSStyleRule
object
in its
attribute,
containing the grid-auto-flow property.
Note: This does mean that the serialization of such rules will differ from how they were originally written, with no directly-nested properties in the serialization.
2.2.1. Nested @scope Rules
When the @scope rule is a nested group rule, an & in the <scope-start> selector refers to the elements matched by the nearest ancestor style rule.
For the purposes of the style rules in its body and its own <scope-end> selector, the @scope rule is treated as an ancestor style rule, matching the elements matched by its <scope-start> selector.
.parent{ color : blue; @scope ( & > .scope) to( & .limit) { & .content{ color : red; } } }
is equivalent to:
.parent{ color : blue; } @scope ( .parent > .scope) to( .parent > .scope .limit) { .parent > .scope .content{ color : red; } }
2.3. Mixing Nesting Rules and Declarations
When a style rule contains both declarations and nested style rules or nested group rules, all three can be arbitrarily mixed. However, the relative order of declarations vs other rules is not preserved in any way.
article{ color : green; &{ color : blue; } color: red; } /* equivalent to */ article{ color : green; color : red; &{ color : blue; } }
For the purpose of determining the Order Of Appearance, nested style rules and nested group rules are considered to come after their parent rule.
article{ color : blue; &{ color : red; } }
Both declarations have the same specificity (0,0,1), but the nested rule is considered to come after its parent rule, so the color: red declarations wins the cascade.
On the other hand, in this example:
article{ color : blue; :where ( &) { color : red; } }
The :where() pseudoclass reduces the specificity of the nesting selector to 0, so the color: red declaration now has a specificity of (0,0,0), and loses to the color: blue declaration before "Order Of Appearance" comes into consideration.
Note: This behavior both matches many existing preprocessor-based nesting behaviors,
and ensures that a rule can be faithfully expressed in the CSSOM
without requiring drastic changes to the existing CSSStyleRule
object.
Note: While one can freely intermix declarations and nested rules, it’s harder to read and somewhat confusing to do so, since all the properties act as if they came before all the rules. For readability’s sake, it’s recommended that authors put all their properties first in a style rule, before any nested rules. (This also happens to act slightly better in older user agents; due to specifics of how parsing and error-recovery work, properties appearing after nested rules can get skipped.)
Note: Like with other types of rules, the serialization of style rules in the presence of nesting can vary from how they were originally written. Notably, all directly-nested properties will be serialized before any nested rules, which is another reason to write properties before rules.
3. Nesting Selector: the & selector
When using a nested style rule, one must be able to refer to the elements matched by the parent rule; that is, after all, the entire point of nesting. To accomplish that, this specification defines a new selector, the nesting selector, written as & (U+0026 AMPERSAND).
When used in the selector of a nested style rule, the nesting selector represents the elements matched by the parent rule. When used in any other context, it represents the same elements as :scope in that context (unless otherwise defined).
a, b{ & c{ color : blue; } }
is equivalent to
:is ( a, b) c{ color : blue; }
The nesting selector cannot represent pseudo-elements (identical to the behavior of the :is() pseudo-class).
.foo, .foo::before, .foo::after{ color : red; &:hover{ color : blue; } }
the & only represents the elements matched by .foo; in other words, it’s equivalent to:
.foo, .foo::before, .foo::after{ color : red; } .foo:hover{ color : blue; }
We’d like to relax this restriction, but need to do so simultaneously for both :is() and &, since they’re intentionally built on the same underlying mechanisms. (Issue 7433)
The specificity of the nesting selector is equal to the largest specificity among the complex selectors in the parent style rule’s selector list (identical to the behavior of :is()).
#a, b{ & c{ color : blue; } } .foo c{ color : red; }
Then in a DOM structure like
< b class = foo > < c > Blue text</ c > </ b >
The text will be blue, rather than red. The specificity of the & is the larger of the specificities of #a ([1,0,0]) and b ([0,0,1]), so it’s [1,0,0], and the entire & c selector thus has specificity [1,0,1], which is larger than the specificity of .foo c ([0,1,1]).
Notably, this is different than the result you’d get if the nesting were manually expanded out into non-nested rules, since the color: blue declaration would then be matching due to the b c selector ([0,0,2]) rather than #a c ([1,0,1]).
Why is the specificity different than non-nested rules?
The nesting selector intentionally uses the same specificity rules as the :is() pseudoclass, which just uses the largest specificity among its arguments, rather than tracking which selector actually matched.
This is required for performance reasons; if a selector has multiple possible specificities, depending on how precisely it was matched, it makes selector matching much more complicated and slower.
That skirts the question, tho: why do we define & in terms of :is()? Some non-browser implementations of Nesting-like functionality do not desugar to :is(), largely because they predate the introduction of :is() as well. Instead, they desugar directly; however, this comes with its own significant problems, as some (reasonably common) cases can accidentally produce massive selectors, due to the exponential explosion of possibilities.
.a1, .a2, .a3{ .b1, .b3, .b3{ .c1, .c2, .c3{ ...; } } } /* naively desugars to */ .a1 .b1 .c1, .a1 .b1 .c2, .a1 .b1 .c3, .a1 .b2 .c1, .a1 .b2 .c2, .a1 .b2 .c3, .a1 .b3 .c1, .a1 .b3 .c2, .a1 .b3 .c3, .a2 .b1 .c1, .a2 .b1 .c2, .a2 .b1 .c3, .a2 .b2 .c1, .a2 .b2 .c2, .a2 .b2 .c3, .a2 .b3 .c1, .a2 .b3 .c2, .a2 .b3 .c3, .a3 .b1 .c1, .a3 .b1 .c2, .a3 .b1 .c3, .a3 .b2 .c1, .a3 .b2 .c2, .a3 .b2 .c3, .a3 .b3 .c1, .a3 .b3 .c2, .a3 .b3 .c3{ ...}
Here, three levels of nesting, each with three selectors in their lists, produced 27 desugared selectors. Adding more selectors to the lists, adding more levels of nesting, or making the nested rules more complex can make a relatively small rule expand into multiple megabytes of selectors (or much, much more!).
Some CSS tools avoid the worst of this by heuristically discarding some variations, so they don’t have to output as much but are still probably correct, but that’s not an option available to UAs.
Desugaring with :is() instead eliminates this problem entirely, at the cost of making specificity slightly less useful, which was judged a reasonable trade-off.
The nesting selector is capable of matching featureless elements, if they were matched by the parent rule.
While the position of a nesting selector in a compound selector does not make a difference in its behavior (that is, &.foo and .foo& match the same elements), the existing rule that a type selector, if present, must be first in the compound selector continues to apply (that is, &div is illegal, and must be written div& instead).
4. CSSOM
Note: [CSSOM-1] now defines
that CSSStyleRule
can have child rules.
When serializing a relative selector in a nested style rule, the selector must be absolutized, with the implied nesting selector inserted.
When serializing a nested group rule, it must serialize solely with child rules.
A nested group rule like:
.foo{ @media ( prefers-color-scheme: dark) { color : white; background : black; } }
will serialize as:
.foo{ @media ( prefers-color-scheme: dark) { &{ color : white; background : black; } } }
Note: These rules ensure that the rules in question are valid to be moved to other contexts, including non-nested ones. It also ensures that the serialization closely matches the structure of the CSSOM.