CSS Nesting Module

Editor’s Draft,

Specification Metadata
This version:
https://drafts.csswg.org/css-nesting/
Issue Tracking:
Inline In Spec
GitHub Issues
Editor:
Tab Atkins Jr. (Google)
Suggest an Edit for this Spec:
GitHub Editor

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.

CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, etc.

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

GitHub Issues are preferred for discussion of this specification. When filing an issue, please put the text “css-nesting” in the title, preferably like this: “[css-nesting] …summary of comment…”. All issues and comments are archived, and there is also a historical archive.

This document was produced by the CSS Working Group.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 1 March 2019 W3C Process Document.

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. This module introduces selectors that extend the [SELECTORS4] module.

1.2. Values

This specification does not define any new properties or values.

1.3. 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.

2. 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 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 :matches() selector. For example,
a, b {
  & c { color: blue; }
}

is equivalent to

:matches(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.

3. Nesting Style Rules

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.

3.1. Direct Nesting

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; }
   :matches(.foo, .bar) + .baz,
   :matches(.foo, .bar).qux { color: red; }
 */

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, .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.

3.2. The Nesting At-Rule: @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 <selector> { <declaration-list> }

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 */

3.3. Mixing Nesting Rules and Declarations

A style rule can have any number of nested style rules inside of it, of either type, intermixed with any number of declarations, in any order.

The relative ordering of nested style rules and other declarations 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.

4. CSS Object Model Modifications

  1. Add an interface for the @nest rule.

  2. Tie into the general work needed to let rules be nested into style rules.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Advisements are normative sections styled to evoke special attention and are set apart from other normative text with <strong class="advisement">, like this: UAs MUST provide an accessible alternative.

Conformance classes

Conformance to this specification is defined for three conformance classes:

style sheet
A CSS style sheet.
renderer
A UA that interprets the semantics of a style sheet and renders documents that use them.
authoring tool
A UA that writes a style sheet.

A style sheet is conformant to this specification if all of its statements that use syntax defined in this module are valid according to the generic CSS grammar and the individual grammars of each feature defined in this module.

A renderer is conformant to this specification if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the features defined by this specification by parsing them correctly and rendering the document accordingly. However, the inability of a UA to correctly render a document due to limitations of the device does not make the UA non-conformant. (For example, a UA is not required to render color on a monochrome monitor.)

An authoring tool is conformant to this specification if it writes style sheets that are syntactically correct according to the generic CSS grammar and the individual grammars of each feature in this module, and meet all other conformance requirements of style sheets as described in this module.

Requirements for Responsible Implementation of CSS

The following sections define several conformance requirements for implementing CSS responsibly, in a way that promotes interoperability in the present and future.

Partial Implementations

So that authors can exploit the forward-compatible parsing rules to assign fallback values, CSS renderers must treat as invalid (and ignore as appropriate) any at-rules, properties, property values, keywords, and other syntactic constructs for which they have no usable level of support. In particular, user agents must not selectively ignore unsupported property values and honor supported values in a single multi-value property declaration: if any value is considered invalid (as unsupported values must be), CSS requires that the entire declaration be ignored.

Implementations of Unstable and Proprietary Features

To avoid clashes with future stable CSS features, the CSSWG recommends following best practices for the implementation of unstable features and proprietary extensions to CSS.

Implementations of CR-level Features

Once a specification reaches the Candidate Recommendation stage, implementers should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec, and should avoid exposing a prefixed variant of that feature.

To establish and maintain the interoperability of CSS across implementations, the CSS Working Group requests that non-experimental CSS renderers submit an implementation report (and, if necessary, the testcases used for that implementation report) to the W3C before releasing an unprefixed implementation of any CSS features. Testcases submitted to W3C are subject to review and correction by the CSS Working Group.

Further information on submitting testcases and implementation reports can be found from on the CSS Working Group’s website at http://www.w3.org/Style/CSS/Test/. Questions should be directed to the public-css-testsuite@w3.org mailing list.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-SYNTAX-3]
Tab Atkins Jr.; Simon Sapin. CSS Syntax Module Level 3. 16 July 2019. CR. URL: https://www.w3.org/TR/css-syntax-3/
[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 7 June 2011. REC. URL: https://www.w3.org/TR/CSS2/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[SELECTORS4]
Elika Etemad; Tab Atkins Jr.. Selectors Level 4. 21 November 2018. WD. URL: https://www.w3.org/TR/selectors-4/

Informative References

[CSS-CASCADE-4]
Elika Etemad; Tab Atkins Jr.. CSS Cascading and Inheritance Level 4. 28 August 2018. CR. URL: https://www.w3.org/TR/css-cascade-4/
[CSS-COLOR-4]
Tab Atkins Jr.; Chris Lilley. CSS Color Module Level 4. 5 November 2019. WD. URL: https://www.w3.org/TR/css-color-4/
[CSS3COLOR]
Tantek Çelik; Chris Lilley; David Baron. CSS Color Module Level 3. 19 June 2018. REC. URL: https://www.w3.org/TR/css-color-3/

Issues Index

  1. Add an interface for the @nest rule.

  2. Tie into the general work needed to let rules be nested into style rules.