Title: CSS Nesting Module
Shortname: css-nesting
Level: 1
Status: ED
Work Status: Exploring
Group: CSSWG
ED: https://drafts.csswg.org/css-nesting/
Editor: Tab Atkins Jr., Google, http://xanthir.com/contact/, w3cid 42199
Editor: Adam Argyle, Google, https://nerdy.dev, w3cid 112669
Abstract: This module introduces the ability to nest one style rule inside another, with the selector of the child rule relative to the selector of the parent rule. This increases the modularity and maintainability of CSS stylesheets.
spec:css-color-4; type:property; text:color
spec:cssom-1; type:dfn;
text:child css rules
text:specified order
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.
Module Interactions
This module introduces new parser rules that extend the [[!CSS21]] parser model.
This module introduces selectors that extend the [[SELECTORS4]] module.
Values
This specification does not define any new properties or values.
Motivation
CSS Rules for even moderately complicated web pages 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 [[CSS3COLOR]] 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:1px 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:1px 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.
Nesting Selector: the ''&'' selector {#nest-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 an ASCII 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 nothing.
(That is, it's valid, but matches no elements.)
The
nesting selector can be desugared
by replacing it with the parent style rule's selector,
wrapped in a '':is()'' selector.
For example,
a, b {
& c { color: blue; }
}
is equivalent to
:is(a, b) c { color: blue; }
The specificity of the nesting selector
is equal to the largest specificity among the parent style rule's selector
that match the given element.
For example, given the following style rules:
#a, .b {
& c { color: blue; }
}
Then in a DOM structure like
<div id=a>
<c>foo</c>
</div>
the ''&'' selector has specificity [1,0,0]
because it matches due to the ''#a'' selector,
giving the entire ''color: blue'' rule a specificity of [1,0,1].
Note: This specificity is intentionally equivalent to that of the desugaring described above.
The nesting selector is allowed anywhere in a compound selector,
even before a type selector,
violating the normal restrictions on ordering within a compound selector.
Note: This is required to allow direct nesting.
Also, the "type selectors must come first" has no intrinsic reason behind it;
it exists because we need to be able to tell simple selectors apart unambiguously
when they're directly appended together in a compound selector,
and it's not clear from ''.foodiv'' that it should mean the same as ''div.foo''.
An ampersand is unambiguously separable from an ident, tho,
so there is no problem with it preceding a type selector,
like ''&div''.
Nesting Style Rules {#nesting}
==============================
Nesting style rules naively inside of other style rules is, unfortunately, problematic--
the syntax of a selector is ambiguous with the syntax of a declaration,
so an implementation requires unbounded lookahead
to tell whether a given bit of text is a declaration or the start of a style rule.
As CSS to date requires only a single token of lookahead in its parsing,
this drawback is generally considered unacceptable among popular implementations of CSS.
To get around this limitation,
this specification defines two methods of nesting style rules inside of other style rules,
both designed to be immediately unambiguous with the surrounding declarations.
The first, direct nesting,
has a somewhat restricted syntax,
but imposes minimal additional "weight" in the form of disambiguating syntax,
and is suitable for most purposes.
The second, the ''@nest'' rule,
imposes a small syntactic weight to disambiguate it from surrounding declarations,
but has no restrictions on the makeup of the selector.
The two are otherwise equivalent,
and either can be used as desired by the stylesheet author.
Direct Nesting {#direct}
------------------------
A style rule can be directly nested
within another style rule if its selector is nest-prefixed.
To be nest-prefixed,
a nesting selector must be the first simple selector
in the first compound selector
of the selector.
If the selector is a list of selectors,
every complex selector in the list must be nest-prefixed
for the selector as a whole to nest-prefixed.
For example, the following nestings are valid:
.foo {
color: blue;
& > .bar { color: red; }
}
/* equivalent to
.foo { color: blue; }
.foo > .bar { color: red; }
*/
.foo {
color: blue;
&.bar { color: red; }
}
/* equivalent to
.foo { color: blue; }
.foo.bar { color: red; }
*/
.foo, .bar {
color: blue;
& + .baz, &.qux { color: red; }
}
/* equivalent to
.foo, .bar { color: blue; }
:is(.foo, .bar) + .baz,
:is(.foo, .bar).qux { color: red; }
*/
.foo {
color: blue;
& .bar & .baz & .qux { color: red; }
}
/* equivalent to
.foo { color: blue; }
.foo .bar .foo .baz .foo .qux { color: red; }
*/
.foo {
color: blue;
& { padding: 2ch; }
}
/* equivalent to
.foo { color: blue; }
.foo { padding: 2ch; }
// and
.foo {
color: blue;
padding: 2ch;
}
*/
.error, #404 {
&:not(.foo,.bar) > .baz { color: red; }
}
/* equivalent to
:is(.error, #404):not(.foo,.bar) > .baz { color: red; }
*/
.foo {
&:is(.bar, &.baz) { color: red; }
}
/* equivalent to
.foo:is(.bar, .foo.baz) { color: red; }
*/
figure {
margin: 0;
& > figcaption {
background: hsl(0 0% 0% / 50%);
& > p {
font-size: .9rem;
}
}
}
/* equivalent to
figure { margin: 0; }
figure > figcaption { background: hsl(0 0% 0% / 50%); }
figure > figcaption > p { font-size: .9rem; }
*/
main {
& > section,
& > article {
background: white;
& > header {
font-size: 1.25rem;
}
}
}
/* equivalent to
main > :is(section, article) { background: white; }
main > :is(section, article) > header { font-size: 1.25rem; }
*/
Note:
BEM authors often use preprocessors to
stay
dry
within a file and selector context,
and preprocessors would concatenate the selectors like strings.
This however is not how it works in browsers. Authors may still practice BEM,
but the nested selector string building technique will need to stay a feature
of preprocessors.
For example:
.foo {
color: blue;
&__bar { padding: 2ch; }
}
/* equivalent to
.foo { color: blue; }
__bar.foo { padding: 2ch; }
*/
''__bar'' is a valid potential
custom element.
But the following are invalid:
.foo {
color: red;
.bar { color: blue; }
}
/* Invalid because there's no nesting selector */
.foo {
color: red;
.bar & { color:blue; }
}
/* Invalid because & isn't in the first compound selector */
.foo {
color: red;
&&.bar { color: blue; }
}
/* Invalid because the second & is no longer
at the start of a compound selector */
.foo {
color: red;
&.bar, .baz { color: blue; }
}
/* Invalid because the second selector in the list doesn't
contain a nesting selector. */
Note: The last invalid example is technically not ambiguous,
but it's still invalid because allowing it would be an editing hazard.
Later edits to the stylesheet might remove the first selector in the list,
making the other one the new "first selector",
and making the rule invalid.
Turning an otherwise-innocuous action
(like removing a selector from a list)
into a possible error
makes editing more complicated,
and is author-hostile,
so we disallow it as a possibility.
The Nesting At-Rule: ''@nest'' {#at-nest}
-----------------------------------------
While direct nesting looks nice,
it is somewhat fragile.
Some valid nesting selectors,
like ''.foo &'',
are disallowed,
and editing the selector in certain ways can make the rule invalid unexpectedly.
As well,
some people find the nesting challenging to distinguish visually
from the surrounding declarations.
To aid in all these issues,
this specification defines the ''@nest'' rule,
which imposes fewer restrictions on how to validly nest style rules.
Its syntax is:
@nest = @nest <> { <> }
The ''@nest'' rule functions identically to a style rule:
it starts with a selector,
and contains declarations that apply to the elements the selector matches.
The only difference is that the selector used in a ''@nest'' rule
must be nest-containing,
which means it contains a nesting selector in it somewhere.
A list of selectors is nest-containing if all of its individual complex selectors
are nest-containing.
For example, the following nestings are valid:
.foo {
color: red;
@nest & > .bar {
color: blue;
}
}
/* equivalent to
.foo { color: red; }
.foo > .bar { color: blue; }
*/
.foo {
color: red;
@nest .parent & {
color: blue;
}
}
/* equivalent to
.foo { color: red; }
.parent .foo { color: blue; }
*/
.foo {
color: red;
@nest :not(&) {
color: blue;
}
}
/* equivalent to
.foo { color: red; }
:not(.foo) { color: blue; }
*/
But the following are invalid:
.foo {
color: red;
@nest .bar {
color: blue;
}
}
/* Invalid because there's no nesting selector */
.foo {
color: red;
@nest & .bar, .baz {
color: blue;
}
}
/* Invalid because not all selectors in the list
contain a nesting selector */
Nesting Conditional Rules {#conditionals}
-----------------------------------------------
A style rule can have any number of conditional rules inside of it, of any type,
intermixed with any number of declarations, in any order.
The presence of a nested conditional engages the same logic as if ''@nest'' was present.
The nested conditional rules must contain a nesting selector and follow the same
rules as outlined in direct nesting.
For example, the following conditional nestings are valid:
.foo {
display: grid;
@media (orientation: landscape) {
& {
grid-auto-flow: column;
}
}
}
/* equivalent to
.foo { display: grid; }
@media (orientation: landscape) {
.foo {
grid-auto-flow: column;
}
}
*/
.foo {
display: grid;
@media (orientation: landscape) {
& {
grid-auto-flow: column;
}
@media (min-inline-size > 1024px) {
& {
max-inline-size: 1024px;
}
}
}
}
/* equivalent to
.foo { display: grid; }
@media (orientation: landscape) {
.foo {
grid-auto-flow: column;
}
}
@media (orientation: landscape) and (min-inline-size > 1024px) {
.foo {
max-inline-size: 1024px;
}
}
*/
.foo {
color: red;
@media (min-width: 480px) {
& > .bar,
& > .baz {
color: blue;
}
}
}
/* equivalent to
.foo { color: red; }
@media (min-width: 480px) {
.foo > :is(.bar, .baz) {
color: blue;
}
}
*/
But the following are invalid:
.foo {
display: grid;
@media (orientation: landscape) {
grid-auto-flow: column;
}
}
/* Invalid because there's no nesting selector */
.foo {
color: red;
@media (min-width: 480px) {
& h1, h2 { color: blue; }
}
}
/* Invalid because not all selectors in the list
contain a nesting selector */
.foo {
color: red;
@nest @media (min-width: 480px) {
& { color: blue; }
}
}
/* Invalid because @nest expects a selector prelude,
instead a conditional rule was provided */
Mixing Nesting Rules and Declarations {#mixing}
-----------------------------------------------
A style rule can have any number of declarations inside of it,
followed by any number of rules.
Declarations occuring after a nested rule
are invalid.
For example,
in the following code:
article {
color: green;
& { color: blue; }
color: red;
}
The ''color: red'' declaration is invalid and ignored,
since it occurs after the [=nested style rule=].
However, further nested rules are still valid,
as in this example:
article {
color: green;
& { color: blue; }
color: red;
&.foo { color: yellow; } /* valid! */
}
The relative ordering of nested style rules and nested conditional rules
is important;
it's possible for a given style rule and a nested style rule within it to match the same element,
and if the specificity of the two rules is otherwise equivalent,
the relative order in the stylesheet of the applicable declarations
determines which declaration "wins" the cascade.
For this purpose,
a nested rule is considered to come after its parent rule.
For example, consider the following where the specificity is the same and the
cascade is used for value resolution:
article {
& .blue { color: blue; } /* (0,1,1) */
& .red { color: red; } /* (0,1,1) */
}
/* equivalent to
article .blue { color: blue; }
article .red { color: red; }
*/
The specificity of ''article .blue'' and ''article .red'' are both (0,1,1).
In this example:
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.
On the other hand, in this example:
article {
color: blue;
@nest :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.
CSSOM {#cssom}
==============
Modifications to {{CSSStyleRule}} {#cssom-style}
---------------------------------------------
CSS style rules gain the ability to have nested rules:
partial interface CSSStyleRule {
[SameObject] readonly attribute CSSRuleList cssRules;
unsigned long insertRule(CSSOMString rule, optional unsigned long index = 0);
undefined deleteRule(unsigned long index);
};
The cssRules attribute
must return a {{CSSRuleList}} object for the [=CSSRule/child CSS rules=].
The insertRule(rule, index) method
must return the result of
invoking [=insert a CSS rule=] rule
into the [=CSSRule/child CSS rules=] at index.
The deleteRule(index) method
must [=remove a CSS rule=] from the [=CSSRule/child CSS rules=] at index.
The {{CSSNestingRule}} Interface {#cssom-nesting}
-------------------------------------------------
The {{CSSNestingRule}} interfaces represents a ''@nest'' rule:
[Exposed=Window]
interface CSSNestingRule : CSSRule {
attribute CSSOMString selectorText;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
[SameObject] readonly attribute CSSRuleList cssRules;
unsigned long insertRule(CSSOMString rule, optional unsigned long index = 0);
undefined deleteRule(unsigned long index);
};
The selectorText attribute,
on getting,
must return the result of [=serialize a group of selectors|serializing=]
the associated [=selector list=].
On setting the {{CSSStyleRule/selectorText}} attribute these steps must be run:
1. Run the parse a group of selectors algorithm on the given value.
2. If the algorithm returns a non-null value replace the associated [=selector list=] with the returned value.
3. Otherwise, if the algorithm returns a null value, do nothing.
The style attribute
must return a {{CSSStyleDeclaration}} object for the style rule,
with the following properties:
: [=CSSStyleDeclaration/computed flag=]
:: Unset.
: [=CSSStyleDeclaration/declarations=]
:: The declared declarations in the rule, in specified order.
: [=CSSStyleDeclaration/parent CSS rule=]
:: The context object.
: [=CSSStyleDeclaration/owner node=]
:: Null.
The cssRules attribute
must return a {{CSSRuleList}} object for the [=CSSRule/child CSS rules=].
The insertRule(rule, index) method
must return the result of
invoking [=insert a CSS rule=] rule
into the [=CSSRule/child CSS rules=] at index.
The deleteRule(index) method
must [=remove a CSS rule=] from the [=CSSRule/child CSS rules=] at index.
To serialize a {{CSSNestingRule}}:
return the result of the following steps:
- Let |s| initially be the string "
@nest
" followed by a single SPACE (U+0020).
- Append to |s| the result of performing serialize a group of selectors on the rule's associated selectors,
followed by the string "
{
", i.e., a single SPACE (U+0020), followed by LEFT CURLY BRACKET (U+007B).
- Let |decls| be the result of performing serialize a CSS declaration block on the rule's associated declarations, or null if there are no such declarations.
- Let |rules| be the result of performing [=serialize a CSS rule=] on each rule in the rule's {{CSSStyleRule/cssRules}} list, or null if there are no such rules.
- If |decls| and |rules| are both null, append " }" to |s| (i.e. a single SPACE (U+0020) followed by RIGHT CURLY BRACKET (U+007D)) and return |s|.
- If |rules| is null:
- Append a single SPACE (U+0020) to |s|
- Append |decls| to |s|
- Append " }" to |s| (i.e. a single SPACE (U+0020) followed by RIGHT CURLY BRACKET (U+007D)).
- Return |s|.
- Otherwise:
- If |decls| is not null, prepend it to |rules|.
- For each |rule| in |rules|:
- Append a newline followed by two spaces to |s|.
- Append |rule| to |s|.
- Append a newline followed by RIGHT CURLY BRACKET (U+007D) to |s|.
- Return |s|.