Jump to Table of Contents Collapse Sidebar

The Wayback Machine - https://webcf.waybackmachine.org/web/20210928083327/https://drafts.csswg.org/css-contain-3/

CSS Containment Module Level 3

Editor’s Draft,

Specification Metadata
This version:
https://drafts.csswg.org/css-contain-3/
Latest published version:
https://www.w3.org/TR/css-contain-3/
Test Suite:
https://test.csswg.org/harness/results/css-contain-1_dev/
Issue Tracking:
CSSWG Issues Repository
Inline In Spec
Editors:
Tab Atkins (Google)
Florian Rivoal (On behalf of Bloomberg)
Miriam E. Suzanne (Invited Expert)
Suggest an Edit for this Spec:
GitHub Editor

Abstract

This CSS module describes the contain property, which indicates that the element’s subtree is independent of the rest of the page. This enables heavy optimizations by user agents when used well.

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.

Please send feedback by filing issues in GitHub (preferred), including the spec code “css-contain” in the title, like this: “[css-contain] …summary of comment…”. All issues and comments are archived. Alternately, feedback can be sent to the (archived) public mailing list www-style@w3.org.

This document is governed by the 15 September 2020 W3C Process Document.

1. Introduction

This is a diff spec over CSS Containment Level 2. It is currently an Exploratory Working Draft: if you are implementing anything, please use Level 2 as a reference. We will merge the Level 2 text into this draft once it reaches CR.

1.1. Module Interactions

This document defines new features not present in earlier specifications. In addition, it aims to replace and supersede [CSS-CONTAIN-1] once stable.

1.2. Value Definitions

This specification follows the CSS property definition conventions from [CSS2] using the value definition syntax from [CSS-VALUES-3]. Value types not defined in this specification are defined in CSS Values & Units [CSS-VALUES-3]. Combination with other CSS modules may expand the definitions of these value types.

In addition to the property-specific values listed in their definitions, all properties defined in this specification also accept the CSS-wide keywords as their property value. For readability they have not been repeated explicitly.

2. Strong Containment: the contain property

contain

Firefox69+SafariNoneChrome52+
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android🔰 41+iOS SafariNoneChrome for Android52+Android WebView52+Samsung Internet6.0+Opera Mobile41+

CSS Containment 2 § 2 Strong Containment: the contain property

Name: contain
New values: layout || style || paint || [ size | inline-size | block-size ]
inline-size
The value turns on inline-size containment for the element. This ensures that the inline containment box can be laid out without needing to examine its descendants.
block-size
The value turns on block-size containment for the element. This ensures that the block containment box can be laid out without needing to examine its descendants.

3. Types of Containment

CSS Containment 2 § 3 Types of Containment

3.1. Inline-Size Containment

Giving an element inline-size containment makes its principal box behave as a size containment box on the inline axis.

Define inline-size containment in more detail <https://github.com/w3c/csswg-drafts/issues/1031>

3.2. Block-Size Containment

Giving an element block-size containment makes its principal box behave as a size containment box on the block axis.

Define block-size containment in more detail <https://github.com/w3c/csswg-drafts/issues/1031>

4. Container Queries

While media queries provide a method to query aspects of the user agent or device environment that a document is being displayed in (such as viewport dimensions or user preferences), container queries allow testing aspects of elements within the document (such as box dimensions or computed styles).

A query container is established by specifying the possible query types using the container-type property (or the container shorthand). Style rules applying to its descendants can then be conditioned by querying against it, using the @container conditional group rule.

For example, we can define the main content area and sidebar as containers, and then describe a .media-object that changes from vertical to horizontal layout depending on the size of its container:
main, aside {
  container: inline-size;
}

.media-object {
  display: grid;
  grid-template: 'img' auto 'content' auto / 100%;
}

@container (inline-size > 45em) {
  .media-object {
    grid-template: 'img content' auto / auto 1fr;
  }
}

Media objects in the main and sidebar areas will each respond to their own container context.

4.1. Creating Query Containers: the container-type property

Name: container-type
Value: none | style || state || [ size | inline-size | block-size ]
Initial: none
Applies to: all elements
Inherited: no
Percentages: n/a
Computed value: the keyword none or one or more of size, inline-size, block-size, style, state
Canonical order: per grammar
Animation type: not animatable

The container-type property establishes the element as a query container for the purpose of container queries, allowing style rules styling its descendants to query various aspects of its sizing, layout, and style and respond accordingly.

Bikeshed terms/property names to avoid confusion with other usage of “contain” and “container”? <https://github.com/w3c/csswg-drafts/issues/6376>

Values have the following meanings:

size
Establishes a query container for size queries on both the inline and block axis. Applies layout containment, style containment, and size containment to the principal box.
inline-size
Establishes a query container for size queries on the container’s own inline axis. Applies layout containment, style containment, and inline-size containment to the principal box.
block-size
Establishes a query container for size queries on the container’s own block axis. Applies layout containment, style containment, and block-size containment to the principal box.
style
Establishes a query container for style queries.
state
Establishes a query container for state queries.
For example, authors can create container-responsive typography, adjusting font-size, line-height, and other typographic concerns based on the size of a container:
aside, main {
  container-type: inline-size;
}

h2 { font-size: 1.2em; }

@container (width > 40em) {
  h2 { font-size: 1.5em; }
}

The 40em value used in the query condition is relative to the computed value of font-size on the relevant query container.

Containers can also expose computed style values for querying. This can be useful for toggling behavior across multiple properties:
section {
  container-type: style;
}

@container (--cards) {
  article {
    border: thin solid silver;
    border-radius: 0.5em;
    padding: 1em;
  }
}

4.2. Naming Query Containers: the container-name property

Name: container-name
Value: none | [ <custom-ident> | <string> ]+
Initial: none
Applies to: all elements
Inherited: no
Percentages: n/a
Computed value: a set of unique identifiers
Canonical order: per grammar
Animation type: not animatable

The container-name property specifies a list of query container names. These names can be used by @container rules to filter which query containers are targeted.

none
The query container has no query container name.
<custom-ident>
Specifies a query container name as an identifier.
<string>
Specifies a query container name as a <string> value; this computes to an identifier with the same value as the given <string>.

The keyword none and the string "none" are invalid as <custom-ident> or <string> values.

In some cases, we want to query aspects of a specific container, even if it’s not the nearest ancestor container. For example, we might want to query the height of a main content area, and the width of a more nested inline-container.
main {
  container-type: size;
  container-name: page-layout;
}

.my-component {
  container-type: inline-size;
  container-name: component-library;
}

@container page-layout (block-size > 12em) {
  .card { margin-block: 2em; }
}

@container component-library (inline-size > 30em) {
  .card { margin-inline: 2em; }
}
Since <string> values are allowed, we can also generate container names from attributes:
[data-container] {
  container-name: attr(data-container);
}

This will set the the query container name to use the contents of the data-container attribute when provided.

4.3. Creating Named Containers: the container shorthand

Name: container
Value: <'container-type'> [ / <'container-name'> ]?
Initial: see individual properties
Applies to: see individual properties
Inherited: see individual properties
Percentages: see individual properties
Computed value: see individual properties
Animation type: see individual properties
Canonical order: per grammar

The container shorthand property sets both container-type and container-name in the same declaration. If <'container-name'> is omitted, it is reset to its initial value.

We can define both a container-type and container-name using the shorthand syntax:
main {
  container: size / layout;
}

.grid-item {
  container: inline-size / component;
}

4.4. Container Queries: the @container rule

The @container rule is a conditional group rule whose condition is a container query, which is a boolean combination of size queries and/or style queries. Style declarations within the <stylesheet> block of an @container rule are filtered by its condition to only match when the container query is true for their element’s query container.

The syntax of the @container rule is:

@container
  [ <container-name> | [ name(<container-name>) || type(<container-type>+) ] ]?
  <container-query> {
    <stylesheet>
}

where:

<container-condition> = not <container-query>
                      | <container-query> [ and <container-query> ]*
                      | <container-query> [ or <container-query> ]*
<container-query>     = ( <container-condition> )
                      | size( <size-query> )
                      | style( <style-query> )

<size-query>     = <size-feature> | <size-condition>
<size-condition> = not ( <size-query> )
                 | ( <size-query> ) [ and ( <size-query> ) ]*
                 | ( <size-query> ) [ or  ( <size-query> ) ]*

<style-query>     = <style-feature> | <style-condition>
<style-condition> = not ( <style-query> )
                  | ( <style-query> ) [ and ( <style-query> ) ]*
                  | ( <style-query> ) [ or  ( <style-query> ) ]*

For each element, the query container to be queried is selected from among the element’s ancestor query containers. The optional <container-name> filters the set of query containers considered to just those with a matching query container name, and the optional <container-type> filters the set to just those with a matching container-type. The nearest remaining query container ancestor is selected.

Should the UA automatically filter to the nearest compatible query container if no specific type is provided?

Do we like this syntax for querying specific container types? <https://github.com/w3c/csswg-drafts/issues/6393>

A query container with a container-type of size is a match for both inline-size and block-size.

Once an eligible query container has been selected for an element, each container feature in the <container-query-list> is evaluated against that query container. If the selected query container is not a valid container-type for the feature, or no ancestor is an eligible query container, then the container query is unknown for that element.

As with media queries, we can string together multiple conditions in a single query list:
@container card (inline-size > 30em) and (--responsive = true) {
  /* styles */
}

The styles above will only be applied if there nearest ancestor container named "card" meets both the inline-size and style conditions.

Style rules defined on an element inside multiple nested container queries apply when all of the wrapping container queries are true for that element.

Note: Nested container queries can evaluate in relation to different containers, so it is not always possible to merge the individual <container-query-list>s into a single query.

5. Container Features

A container feature queries a specific aspect of a query container.

What container features can be queried? <https://github.com/w3c/csswg-drafts/issues/5989>

5.1. Size Container Features

A size query (syntactically represented as <size-query>) allows querying the size of the query container’s principal box. It is a boolean combination of individual size features (<size-feature>) that each query a single, specific dimensional feature of the query container. The syntax of a <size-feature> is the same as for a media feature: a feature name, a comparator, and a value. [mediaqueries-5] The boolean syntax and logic combining size features into a <size-query> is the same as for feature queries. (See @supports. [CSS-CONDITIONAL-3])

If the query container does not have a principal box, or the principal box is not a layout containment box, or the query container does not support size queries on the relevant axes, then the result of evaluating the size feature is unknown.

Relative length units in container query conditions are evaluated based on the the computed values of the query container.

Note: This is different from the handling of relative units in media queries.

For example, query containers with different font-sizes will evaluate em-based queries relative to their own font sizes:
aside, main {
  container-type: inline-size;
}

aside { font-size: 16px; }
main { font-size: 24px; }

@container (width > 40em) {
  h2 { font-size: 1.5em; }
}

The 40em value used in the query condition is relative to the computed value of font-size on the relevant query container:

5.1.1. Width: the width feature

Name: width
For: @container
Value: <length>
Type: range

The width container feature queries the width of the query container’s content box.

5.1.2. Height: the height feature

Name: height
For: @container
Value: <length>
Type: range

The height container feature queries the height of the query container’s content box.

5.1.3. Inline-size: the inline-size feature

Name: inline-size
For: @container
Value: <length>
Type: range

The inline-size container feature queries the size of the query container’s content box in the query container’s inline axis.

5.1.4. Block-size: the block-size feature

Name: block-size
For: @container
Value: <length>
Type: range

The block-size container feature queries the size of the query container’s content box in the query container’s block axis.

5.1.5. Aspect-ratio: the aspect-ratio feature

Name: aspect-ratio
For: @container
Value: <ratio>
Type: range

The aspect-ratio container feature is defined as the ratio of the value of the width container feature to the value of the height container feature.

5.1.6. Orientation: the orientation feature

Name: orientation
For: @container
Value: portrait | landscape
Type: discrete
portrait
The orientation container feature is portrait when the value of the height container feature is greater than or equal to the value of the width container feature.
landscape
Otherwise orientation is landscape.

5.2. Style Container Features

A style queries (syntactically represented by <style-query>) allows querying the computed values of the query container. It is a boolean combination of individual style features (<style-feature>) that each query a single, specific property of the query container. The syntax of a <style-feature> is the same as for a declaration [CSS-SYNTAX-3], and its query is true if the computed value of the given property on the query container matches the given value (which is also computed with respect to the query container), unknown if the property or its value is unsupported, and false otherwise. The boolean syntax and logic combining style features into a <style-query> is the same as for feature queries. (See @supports. [CSS-CONDITIONAL-3])

Do we like this proposed syntax for style queries? <https://github.com/w3c/csswg-drafts/issues/6396>

5.3. State Container Features

State queries allow querying miscellaneous query container states, such as whether a position: sticky box is displaced from its in-flow position, or whether the box is visible on screen.

Define a syntax for state-based container queries <https://github.com/w3c/csswg-drafts/issues/6402>

6. Container Relative Lengths: the qw, qh, qi, qb, qmin, qmax units

Query length units specify a length relative to the dimensions of a query container. Style sheets that use query length units can more easily move components from one query container to another.

The query length units are:

Informative Summary of Container Units
unit relative to
qw 1% of a query container’s width
qh 1% of a query container’s height
qi 1% of a query container’s inline size
qb 1% of a query container’s block size
qmin The smaller value of qi or qb
qmax The larger value of qi or qb

For each element, query length units are evaluated as size queries on the relevant axis (or axes) described by the unit. The query container for each axis is the nearest ancestor container that accepts size queries on that axis. If no eligible query container is available, then use the small viewport size for that axis.

Note: In some cases qi and qb units on the same element will evaluate in relation to different query containers. Similarly, qmin and qmax units represent the larger or smaller of the qi and qb units, even when those dimensions come from different query containers.

Child elements do not inherit the relative values as specified for their parent; they inherit the computed values.

Authors can ensure that query length units have an appropriate query container by applying them inside a container query with the required <container-type>. Custom fallback values can be defined outside the container query:
/* The fallback value does not rely on containment */
h2 { font-size: 1.2em; }

@container type(inline-size) {
  /* only applies when an inline-size container is available */
  h2 { font-size: calc(1.2em + 1qi); }
}

"container width" and "container height" units <https://github.com/w3c/csswg-drafts/issues/5888>

7. Suppressing An Element’s Contents Entirely: the content-visibility property

content-visibility

In only one current engine.

FirefoxNoneSafariNoneChrome85+
Opera71+Edge85+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android85+Android WebView85+Samsung Internet14.0+Opera Mobile60+

CSS Containment 2 § 4 Suppressing An Element’s Contents Entirely: the content-visibility property

8. Privacy and Security Considerations

CSS Containment 2 § 5 Privacy and Security Considerations

Appendix A. Changes

This appendix is informative.

Changes from CSS Containment Level 2

CSS Containment 2 §  Changes

Acknowledgments

Comments and previous work from Adam Argyle, Amelia Bellamy-Royds, Anders Hartvoll Ruud, Brian Kardell, Chris Coyier, Christopher Kirk-Nielsen, David Herron, Elika J. Etemad (fantasai), Eric Portis, Ethan Marcotte, Geoff Graham, Gregory Wild-Smith, Ian Kilpatrick, Jen Simmons, Kenneth Rohde Christiansen, L. David Baron, Lea Verou, Martin Auswöger, Martine Dowden, Mike Riethmuller, Morten Stenshorne, Nicole Sullivan, Rune Lillesveen, Scott Jehl Scott Kellum, Stacy Kvernmo, Theresa O’Connor, Una Kravets, and many others have contributed to this specification.

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.

Tests

Tests relating to the content of this specification may be documented in “Tests” blocks like this one. Any such block is non-normative.


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.

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

Non-experimental implementations

Once a specification reaches the Candidate Recommendation stage, non-experimental implementations are possible, and implementors should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec.

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-BOX-4]
Elika Etemad. CSS Box Model Module Level 4. 21 April 2020. WD. URL: https://www.w3.org/TR/css-box-4/
[CSS-CASCADE-5]
Elika Etemad; Miriam Suzanne; Tab Atkins Jr.. CSS Cascading and Inheritance Level 5. 29 August 2021. WD. URL: https://www.w3.org/TR/css-cascade-5/
[CSS-CONDITIONAL-3]
David Baron; Elika Etemad; Chris Lilley. CSS Conditional Rules Module Level 3. 8 December 2020. CR. URL: https://www.w3.org/TR/css-conditional-3/
[CSS-CONTAIN-1]
Tab Atkins Jr.; Florian Rivoal. CSS Containment Module Level 1. 22 December 2020. REC. URL: https://www.w3.org/TR/css-contain-1/
[CSS-CONTAIN-2]
Tab Atkins Jr.; Florian Rivoal; Vladimir Levin. CSS Containment Module Level 2. 16 December 2020. WD. URL: https://www.w3.org/TR/css-contain-2/
[CSS-DISPLAY-3]
Tab Atkins Jr.; Elika Etemad. CSS Display Module Level 3. 3 September 2021. CR. URL: https://www.w3.org/TR/css-display-3/
[CSS-POSITION-3]
Elika Etemad; et al. CSS Positioned Layout Module Level 3. 19 May 2020. WD. URL: https://www.w3.org/TR/css-position-3/
[CSS-SIZING-3]
Tab Atkins Jr.; Elika Etemad. CSS Box Sizing Module Level 3. 17 March 2021. WD. URL: https://www.w3.org/TR/css-sizing-3/
[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/
[CSS-VALUES-3]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 3. 6 June 2019. CR. URL: https://www.w3.org/TR/css-values-3/
[CSS-VALUES-4]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 4. 15 July 2021. WD. URL: https://www.w3.org/TR/css-values-4/
[CSS-WRITING-MODES-4]
Elika Etemad; Koji Ishii. CSS Writing Modes Level 4. 30 July 2019. CR. URL: https://www.w3.org/TR/css-writing-modes-4/
[CSS2]
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/CSS21/
[MEDIAQUERIES-5]
Dean Jackson; Florian Rivoal; Tab Atkins Jr.. Media Queries Level 5. 31 July 2020. WD. URL: https://www.w3.org/TR/mediaqueries-5/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119

Informative References

[CSS-FONTS-5]
Myles Maxfield; Chris Lilley. CSS Fonts Module Level 5. 29 July 2021. WD. URL: https://www.w3.org/TR/css-fonts-5/

Property Index

Name Value Initial Applies to Inh. %ages Anim­ation type Canonical order Com­puted value
container <'container-type'> [ / <'container-name'> ]? see individual properties see individual properties see individual properties see individual properties see individual properties per grammar see individual properties
container-name none | [ <custom-ident> | <string> ]+ none all elements no n/a not animatable per grammar a set of unique identifiers
container-type none | style || state || [ size | inline-size | block-size ] none all elements no n/a not animatable per grammar the keyword none or one or more of size, inline-size, block-size, style, state

@container Descriptors

Name Value Initial Type
aspect-ratio <ratio> range
block-size <length> range
height <length> range
inline-size <length> range
orientation portrait | landscape discrete
width <length> range

Issues Index

This is a diff spec over CSS Containment Level 2. It is currently an Exploratory Working Draft: if you are implementing anything, please use Level 2 as a reference. We will merge the Level 2 text into this draft once it reaches CR.
CSS Containment 2 § 2 Strong Containment: the contain property
CSS Containment 2 § 3 Types of Containment
Define inline-size containment in more detail <https://github.com/w3c/csswg-drafts/issues/1031>
Define block-size containment in more detail <https://github.com/w3c/csswg-drafts/issues/1031>
Bikeshed terms/property names to avoid confusion with other usage of “contain” and “container”? <https://github.com/w3c/csswg-drafts/issues/6376>
Should the UA automatically filter to the nearest compatible query container if no specific type is provided?
Do we like this syntax for querying specific container types? <https://github.com/w3c/csswg-drafts/issues/6393>
What container features can be queried? <https://github.com/w3c/csswg-drafts/issues/5989>
Do we like this proposed syntax for style queries? <https://github.com/w3c/csswg-drafts/issues/6396>
Define a syntax for state-based container queries <https://github.com/w3c/csswg-drafts/issues/6402>
"container width" and "container height" units <https://github.com/w3c/csswg-drafts/issues/5888>
CSS Containment 2 § 4 Suppressing An Element’s Contents Entirely: the content-visibility property
CSS Containment 2 § 5 Privacy and Security Considerations
CSS Containment 2 §  Changes