CSS Grid Layout Module Level 2

W3C Working Draft,

This version:
https://www.w3.org/TR/2018/WD-css-grid-2-20180804/
Latest published version:
https://www.w3.org/TR/css-grid-2/
Editor's Draft:
https://drafts.csswg.org/css-grid-2/
Previous Versions:
Issue Tracking:
Inline In Spec
GitHub Issues
Editors:
Tab Atkins Jr. (Google)
Elika J. Etemad / fantasai (Invited Expert)
(Microsoft)

Abstract

This CSS module defines a two-dimensional grid-based layout system, optimized for user interface design. In the grid layout model, the children of a grid container can be positioned into arbitrary slots in a predefined flexible or fixed-size layout grid. Level 2 expands Grid by adding “subgrid” capabilities for nested grids to participate in the sizing of their parent grids; and aspect-ratio–controlled gutters.

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

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

GitHub Issues are preferred for discussion of this specification. When filing an issue, please put the text “css-grid” in the title, preferably like this: “[css-grid] …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 (part of the Style Activity).

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 February 2018 W3C Process Document.

1. Introduction

This level is currently maintained as a diff spec over the level 1 module [CSS-GRID-1]. The main addition to Level 1 is the “subgrid” feature: a subgridded axis is one which matches up its grid lines to lines in the element’s parent’s grid, and which derives the sizes of its tracks through this integration with the parent grid. In general, the behavior of subgrids are the same in both proposals: it is only a question of whether a single-axis subgrid is possible.

The full text of the Grid specification will be folded in when this draft reaches CR.

2. Subgrids

A grid item can itself be a grid container by giving it display: grid; in this case the layout of its contents will be independent of the layout of the grid it participates in.

In some cases it might be necessary for the contents of multiple grid items to align to each other. A grid container that is itself a grid item can defer the definition of its rows and columns to its parent grid container, making it a subgrid. In this case, the grid items of the subgrid participate in sizing the grid of the parent grid container, allowing the contents of both grids to align.

For example, suppose we have a form consisting of a list of inputs with labels:
<ul>
  <li><label>Name:</label> <input name=fn>
  <li><label>Address:</label> <input name=address>
  <li><label>Phone:</label> <input name=phone>
</ul>

We want the labels and inputs to align, and we want to style each list item with a border. This can be accomplished with subgrid layout:

ul {
  display: grid;
  grid: auto-flow / auto 1fr;
}
li {
  grid-column: span 2;
  display: grid;
  grid-template-columns: subgrid;
  border: solid;
}
label {
  grid-column: 1;
}
input {
  grid-column: 2;
}

2.1. Establishing a Subgrid

Subgrids provide the ability to pass grid parameters down through nested elements, and content-based sizing information back up to their parent grid.

Name: grid-template-rows, grid-template-columns
New values: subgrid <line-name-list>?
subgrid <line-name-list>?
The subgrid value indicates that the grid will adopt the spanned portion of its parent grid in that axis. Rather than being specified explicitly, the sizes of the grid rows/columns will be taken from the parent grid’s definition, and the subgrid’s items will participate in the intrinsic size calculations (CSS Grid Layout 1 §11.5 Resolve Intrinsic Track Sizes) of any tracks shared with the parent grid.

The <line-name-list> argument allows local naming of the grid lines propagated from the parent grid: if a <line-name-list> is given, the specified <line-names>s are assigned to the subgrid’s explicit grid lines, one per line, starting with line 1. Excess <line-names> are ignored.

If there is no parent grid, this value is equivalent to the initial value, none.

Unlike those of a regular nested grid, a subgrid’s contents participate in its parent grid formatting contex; thus a subgrid does not establish an independent formatting context.

The syntax of <line-name-list> is defined as follows:

<line-name-list> = [ <line-names> | <name-repeat> ]+
<line-names>     = '[' <custom-ident>* ']'
<name-repeat>    = repeat( [ <positive-integer> | auto-fill ], <line-names>+)

The <name-repeat> variant of the repeat() notation can only be used with the subgrid keyword: it only repeats names. The auto-fill keyword is only valid once per <line-name-list>, and repeats enough times for the name list to match the subgrid’s specified grid span (falling back to 0 if the span is already fulfilled).

2.2. Characteristics of a Subgrid Item

A subgrid behaves just like a normal grid container except that:

2.3. Subgrid Sizing Algorithm

Note: Placement of all grid items, including subgrids and their sub-items, occurs before sizing.

Track sizing in a subgridded dimension treats each item in a given track in that axis as members of the parent grid. This interlacing requires that grid sizing drills down per axis into subgrids, rather than completing both axes in its recursion. Thus the Grid Sizing Algorithm is modified as follows:

  1. First, the track sizing algorithm is used to resolve the sizes of the grid columns.

    In this process, any grid item which is subgridded in the grid container’s inline axis is treated as empty and its grid items (the grandchildren) are treated as direct children of the grid container (their grandparent). This introspection is recursive.

    Items which are subgridded only in the block axis, and whose grid container size in the inline axis depends on the size of its contents are also introspected: since the size of the item in this dimension can be dependent on the sizing of its subgridded tracks in the other, the size contribution of any such item to this grid’s column sizing (see Resolve Intrinsic Track Sizes) is taken under the provision of having determined its track sizing only up to the same point in the Grid Sizing Algorithm as this parent grid itself. E.g. for the first pass through this step, the item will have its tracks sized only through this first step; if a second pass of this step is triggered then the item will have completed a first pass through steps 1-3 as well as the second pass of this step prior to returning its size for consideration in this grid’s column sizing. Again, this introspection is recursive.

    If calculating the layout of a grid item in this step depends on the available space in the block axis, assume the available space that it would have if any row with a definite max track sizing function had that size and all other rows were infinite.

  2. Next, the track sizing algorithm resolves the sizes of the grid rows, using the grid column sizes calculated in the previous step.

    In this process, any grid item which is subgridded in the grid container’s block axis is treated as empty and its grid items (the grandchildren) are treated as direct children of the grid container (their grandparent). This introspection is recursive.

    As with sizing columns, items which are subgridded only in the inline axis, and whose grid container size in the block axis depends on the size of its contents are also introspected. (As with sizing columns, the size contribution to this grid’s row sizing is taken under the provision of having determined its track sizing only up to this corresponding point in the algorithm; and again, this introspection is recursive.)

  3. Then, if the min-content contribution of any grid items have changed based on the row sizes calculated in step 2, steps 1 and 2 are repeated with the new min-content contribution and max-content contribution (once only).
    This cycle is necessary for cases where the inline size of a grid item depends on the block size of its grid area. Examples include wrapped column flex containers (flex-flow: column wrap), orthogonal flows (writing-mode), and multi-column containers.
  4. Finally, the grid container is sized using the resulting size of the grid as its content size, and the tracks are aligned within the grid container according to the align-content and justify-content properties.

    Note: This can introduce extra space between tracks, potentially enlarging the grid area of any grid items spanning the gaps beyond the space allotted to during track sizing.

Once the size of each grid area is thus established, the grid items are laid out into their respective containing blocks. The grid area’s width and height are considered definite for this purpose.

Note: Since formulas calculated using only definite sizes, such as the stretch fit formula, are also definite, the size of a grid item which is stretched is also considered definite.

Note, this means that a subgrid establishing an orthogonal flow would have the order of its track sizing inverted compared to a nested grid. We could simplify this by saying that an orthogonal flow cannot establish a subgrid; it can only be a nested grid.

The following example illustrates how per-axis subgrids are sized:

Suppose we have a parent grid container A which contains an item B that has subgridded columns and contains a grandchild B that has subgridded rows and grandchild D that is simply a nested grid.

<grid-A>
  <grid-B subgrid=columns>
    <grid-C subgrid=rows/>
    <grid-D>
  </grid-B>
<grid-A>

When A sizes its columns it treats B’s items as slotted into to A’s corresponding columns, but when A sizes its rows it treates B as a single item (a grid container with its own rows and some items including items C and D). Similarly when B sizes its rows, it treats C’s items as slotted into B’s rows, but when B sizes its columns, it treats C as a single item, just as it does with D. There is no relationship between C’s rows and A’s rows, because the rows in B are nested, not subgridded.

At a high level, the grid algorithm is:

  1. Size the columns
  2. Size the rows
  3. Adjust the columns (if needed based on final row sizes)

The grid sizing algorithm in this example would thus look like this:

  1. Resolve sizes of A’s grid columns, using the sizes of A’s grid items, treating B as empty but treating its children (including C and D) as items in grid A.

    The grid algorithm simply recurses into D. For C, it’s more complicated:

    1. Size C’s columns.
    2. Size C’s rows by sizing B’s rows.
    3. Adjust C’s columns.
    4. Return C’s final column sizes.

    A correct size for B’s rows requires C’s final column sizes, because the row size depends on the column size, and thus B’s rows could very well depend on C’s final column sizes. To break this cyclic dependency, we need to split the algorithm to depend on the initial approximation of C’s final column sizes, and do the adjustment pass later. So for C, we need to recurse into column sizing only, and pass that initial size up to A for its initial column sizing.

    When we size B’s rows later on, we will size C’s rows (which are subgridded), and finish up C’s sizing by finalizing its columns. If this resulted in a change, we have the opportunity to trigger an adjustment pass for A’s columns during its adjustment pass.

  2. Next, resolve sizes of A’s rows, using the sizes of A’s grid items, treating B as a single item.

    Since B, as a subgrid, has its sizing is split out into the multiple passes, the grid algorithm issues only a row-sizing recursion into B: Size B’s rows, treating D as a single item, requesting its final size, and treating C as an empty item and hoisting its children as items into grid B.

    B returns its final row size, which factors into A’s row sizing pass.

  3. Last, finalize A’s column sizes. If C’s final size changes as a result of the row-sizing pass through B, this should trigger a resizing of B’s columns, which should trigger a resizing pass on A’s column.

3. Aspect-ratio–controlled Gutters

There’s a desire for having row and column gaps maintain a particular aspect ratio. This is one proposal for doing so; other ideas are welcome. See discussion in Issue 1116. Note this feature is likely to move to css-align-4, it is just being drafted up here while css-align-3 stabilizes.

Name: align-content, justify-content
New values: [ <aspect-ratio> <content-distribution>? ]
<aspect-ratio>
A dimension with the unit ar, representing a multiplier against the analogous quantity in the other dimension. If that quantity cannot be determined (e.g. is itself specified as a <aspect-ratio>, or otherwise can’t be referenced), then it is assumed to be zero.

Note: This value can expand gutters even when there is no free space left, causing overflow.

Specifically, an align-content value of 1ar represents the amount of space (which may be zero) allocated between two adjacent alignment subjects (grid tracks / flex lines / column boxes) by the justify-content property. Unless a different <content-distribution> value is specified, space is distributed according to the same <content-distribution> rules as for justify-content. The behavior of <number> values for justify-content is analogous.

Note: The space allocated by align-content: 1ar will be zero if justify-content does not allocate space between adjacent alignment subjects: either due to not having a <content-distribution> value or due to there being fewer than two alignment subjects.

If both align-content and justify-content have <number> values, then justify-content’s <number> value is ignored and its <content-distribution> value honored as if specified alone. fIf no <content-distribution> value was specified, then justify-content takes align-content’s <content-distribution> value (if one was specified) and otherwise falls back to space-between.

In this example, a minimum of 1em is required between rows and columns. Additionally, any extra space in the inline axis that is distributed between columns, with full-size spaces on either side of the outermost columns. The gaps between rows are increased to match the extra space distributed between adjacent columns, but no space is added before the first row or after the last one.
.grid {
  grid-template-columns: repeat(auto-fill, 15em);
  gap: 1em;
  justify-content: space-evenly;
  align-content: 1ar space-between;
}

This next example is the same as the previous, except that the ratio between row and column gaps is φ:

.grid {
  grid-template-columns: repeat(auto-fill, 15em);
  gap: 1em 1.618em;
  justify-content: space-evenly;
  align-content: 0.618ar space-between;
}

4. Changes

Changes since the June 2018 CSS Grid Layout Level 2 Working Draft

Changes since the April 2018 CSS Grid Layout Level 2 Working Draft

5. Acknowledgements

Many thanks to Mats Palmgren of Mozilla, without whose support and feedback the subgrid feature would not be able to move forward. Thanks also to Daniel Tonon, who insisted on intelligent handling of gaps in subgrids and contributed illustrations; and Rachel Andrew and Jen Simmons who helped bridge the feedback gap between the CSS Working Group and the Web design/authoring community.

Lastly, the acknowledgements section of CSS Grid Level 2 would be incomplete without acknowledgement of everyone who made the monumental task of CSS Grid Level 1 possible.

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 https://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-ALIGN-3]
Elika Etemad; Tab Atkins Jr.. CSS Box Alignment Module Level 3. 23 April 2018. WD. URL: https://www.w3.org/TR/css-align-3/
[CSS-DISPLAY-3]
Tab Atkins Jr.; Elika Etemad. CSS Display Module Level 3. 20 April 2018. WD. URL: https://www.w3.org/TR/css-display-3/
[CSS-FLEXBOX-1]
Tab Atkins Jr.; Elika Etemad; Rossen Atanassov. CSS Flexible Box Layout Module Level 1. 19 October 2017. CR. URL: https://www.w3.org/TR/css-flexbox-1/
[CSS-GRID-1]
Tab Atkins Jr.; Elika Etemad; Rossen Atanassov. CSS Grid Layout Module Level 1. 14 December 2017. CR. URL: https://www.w3.org/TR/css-grid-1/
[CSS-MULTICOL-1]
Florian Rivoal; Rachel Andrew. CSS Multi-column Layout Module Level 1. 28 May 2018. WD. URL: https://www.w3.org/TR/css-multicol-1/
[CSS-OVERFLOW-3]
David Baron; Florian Rivoal. CSS Overflow Module Level 3. 31 May 2016. WD. URL: https://www.w3.org/TR/css-overflow-3/
[CSS-RUBY-1]
Elika Etemad; Koji Ishii. CSS Ruby Layout Module Level 1. 5 August 2014. WD. URL: https://www.w3.org/TR/css-ruby-1/
[CSS-SIZING-3]
Tab Atkins Jr.; Elika Etemad. CSS Intrinsic & Extrinsic Sizing Module Level 3. 4 March 2018. WD. URL: https://www.w3.org/TR/css-sizing-3/
[CSS-VALUES-3]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 3. 29 September 2016. CR. URL: https://www.w3.org/TR/css-values-3/
[CSS-WRITING-MODES-4]
Elika Etemad; Koji Ishii. CSS Writing Modes Level 4. 24 May 2018. CR. URL: https://www.w3.org/TR/css-writing-modes-4/
[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

Property Index

No properties defined.

Issues Index

The full text of the Grid specification will be folded in when this draft reaches CR.
Note, this means that a subgrid establishing an orthogonal flow would have the order of its track sizing inverted compared to a nested grid. We could simplify this by saying that an orthogonal flow cannot establish a subgrid; it can only be a nested grid.
There’s a desire for having row and column gaps maintain a particular aspect ratio. This is one proposal for doing so; other ideas are welcome. See discussion in Issue 1116. Note this feature is likely to move to css-align-4, it is just being drafted up here while css-align-3 stabilizes.