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.

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

This document was produced by the CSS Working Group (part of the Style Activity)
as a Candidate Recommendation. This document is intended to become a W3C Recommendation.
This document will remain a Candidate Recommendation at least until 1 May 2017 in order
to ensure the opportunity for wide review.

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.

Publication as a Candidate Recommendation 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.

“At-risk” is a W3C Process term-of-art, and does not necessarily imply that the feature is in danger of being dropped or delayed. It means that the WG believes the feature may have difficulty being interoperably implemented in a timely manner, and marking it as such allows the WG to drop the feature if necessary when transitioning to the Proposed Rec stage, without having to publish a new Candidate Rec without the feature first.

If you notice any inconsistencies between this Grid Layout Module
and the Flexible Box Layout Module,
please report them to the CSSWG,
as this is likely an error.

1. Introduction

This section is not normative.

Grid Layout is a new layout model for CSS
that has powerful abilities to control the sizing and positioning of boxes and their contents.
Unlike Flexible Box Layout, which is single-axis–oriented,
Grid Layout is optimized for 2-dimensional layouts:
those in which alignment of content is desired in both dimensions.

Exemplary Flex Layout ExampleExemplary Grid Layout Example

In addition, due to its ability to explicitly position items in the grid,
Grid Layout allows dramatic transformations in visual layout structure
without requiring corresponding markup changes.
By combining media queries with the CSS properties that control layout of the grid container and its children,
authors can adapt their layout to changes in device form factors, orientation, and available space,
while preserving a more ideal semantic structuring of their content
across presentations.

Although many layouts can be expressed with either Grid or Flexbox,
they each have their specialties.
Grid enforces 2-dimensional alignment,
uses a top-down approach to layout,
allows explicit overlapping of items,
and has more powerful spanning capabilities.
Flexbox focuses on space distribution within an axis,
uses a simpler bottom-up approach to layout,
can use a content-size–based line-wrapping system to control its secondary axis,
and relies on the underlying markup hierarchy
to build more complex layouts.
It is expected that both will be valuable
and complementary tools for CSS authors.

2. Overview

This section is not normative.

Grid Layout controls the layout of its content
through the use of a grid:
an intersecting set of horizontal and vertical lines
which create a sizing and positioning coordinate system
for the grid container’s contents.
Grid Layout features

Grid containers can be nested or mixed with flex containers as necessary to create more complex layouts.
Furthermore, subgrids provide the ability to pass grid parameters down through nested elements, and content-based sizing information back up to their parent grid.

The following declares a grid with four named areas: H, A, B,
and F.
The first column is sized to fit its contents (auto),
and the second column takes up the remaining space (1fr).
Rows default to auto (content-based) sizing;
the last row is given a fixed size of 30px.

main {
grid: "H H "
"A B "
"F F " 30px
/ auto 1fr;
}

The following declares a grid with as many rows of at least 5em as will fit in the height of the grid container (100vh).
The grid has no explicit columns;
instead columns are added as content is added,
the resulting column widths are equalized (1fr)
Since content overflowing to the right won’t print,
an alternate layout for printing adds rows instead.

2.3. Sizing the Grid

Once the grid items have been placed,
the sizes of the grid tracks (rows and columns) are calculated,
accounting for the sizes of their contents and/or available space as specified in the grid definition.

2.4. Background and Motivation

As websites evolved from simple documents into complex, interactive applications,
techniques for document layout, e.g. floats,
were not necessarily well suited for application layout.
By using a combination of tables, JavaScript, or careful measurements on floated elements,
authors discovered workarounds to achieve desired layouts.
Layouts that adapted to the available space were often brittle
and resulted in counter-intuitive behavior as space became constrained.
As an alternative, authors of many web applications opted for a fixed layout
that cannot take advantage of changes in the available rendering space on a screen.

The capabilities of grid layout address these problems.
It provides a mechanism for authors to divide available space for layout into columns and rows
using a set of predictable sizing behaviors.
Authors can then precisely position and size the building block elements of their application
into the grid areas defined by the intersections of these columns and rows.
The following examples illustrate the adaptive capabilities of grid layout,
and how it allows a cleaner separation of content and style.

2.4.1. Adapting Layouts to Available Space

Five grid items arranged according to content size and available space.Growth in the grid due to an increase in available space.

Grid layout can be used to intelligently resize elements within a webpage.
The figures above represent a game with five major components in the layout:
the game title, stats area, game board, score area, and control area.
The author’s intent is to divide the space for the game such that:

The stats area always appears immediately under the game title.

The game board appears to the right of the stats and title.

The top of the game title and the game board should always align.

The bottom of the game board and bottom of the stats area align when the game has reached its minimum height.
In all other cases the game board will stretch to take advantage of all the space available to it.

The controls are centered under the game board.

The top of the score area is aligned to the top of the controls area.

The score area is beneath the stats area.

The score area is aligned to the controls beneath the stats are.

The following grid layout example shows how an author might achieve
all the sizing, placement, and alignment rules declaratively.

2.4.2. Source-Order Independence

Continuing the prior example,
the author also wants the game to adapt to different devices.
Also, the game should optimize the placement of the components when viewed either in portrait or landscape orientation (Figures 4 and 5).
By combining grid layout with media queries,
the author is able to use the same semantic markup,
but rearrange the layout of elements independent of their source order,
to achieve the desired layout in both orientations.

The following example uses grid layout’s ability to name the space which will be occupied by a grid item.
This allows the author to avoid rewriting rules for grid items as the grid’s definition changes.

Note: The reordering capabilities of grid layout intentionally affect only the visual rendering,
leaving speech order and navigation based on the source order.
This allows authors to manipulate the visual presentation
while leaving the source order intact and optimized for non-CSS UAs
and for linear models such as speech and sequential navigation.

Grid item placement and reordering must not be used
as a substitute for correct source ordering,
as that can ruin the accessibility of the document.

3.1. Grid Lines

Grid lines are the horizontal and vertical dividing lines of the grid.
A grid line exists on either side of a column or row.
They can be referred to by numerical index,
or by an author-specified name.
A grid item references the grid lines to determine its position within the grid using the grid-placement properties.

3.2. Grid Tracks and Cells

Grid track is a generic term for a grid column or grid row—in
other words, it is the space between two adjacent grid lines.
Each grid track is assigned a sizing function,
which controls how wide or tall the column or row may grow,
and thus how far apart its bounding grid lines are.
Adjacent grid tracks can be separated by gutters but are otherwise packed tightly.

A grid cell is the intersection of a grid row and a grid column.
It is the smallest unit of the grid that can be referenced when positioning grid items.

In the following example there are two columns and three rows.
The first column is fixed at 150px.
The second column uses flexible sizing, which is a function of the unassigned space in the grid,
and thus will vary as the width of the grid container changes.
If the used width of the grid container is 200px, then the second column is 50px wide.
If the used width of the grid container is 100px, then the second column is 0px
and any content positioned in the column will overflow the grid container.

4. Reordering and Accessibility

Grid layout gives authors great powers of rearrangement over the document.
However, these are not a substitute for correct ordering of the document source.
The order property and grid placementdo not affect ordering in non-visual media
(such as speech).
Likewise, rearranging grid items visually does not affect
the default traversal order of sequential navigation modes
(such as cycling through links, see e.g. tabindex[HTML5]).

Authors must use order and the grid-placement properties only for visual, not logical, reordering of content.
Style sheets that use these features to perform logical reordering are non-conforming.

Note: This is so that non-visual media and non-CSS UAs,
which typically present content linearly,
can rely on a logical source order,
while grid layout’s placement and ordering features are used to tailor the visual arrangement.
(Since visual perception is two-dimensional and non-linear,
the desired visual order is not always equivalent to the desired reading order.)

Many web pages have a similar shape in the markup,
with a header on top,
a footer on bottom,
and then a content area and one or two additional columns in the middle.
Generally,
it’s desirable that the content come first in the page’s source code,
before the additional columns.
However, this makes many common designs,
such as simply having the additional columns on the left and the content area on the right,
difficult to achieve.
This has been addressed in many ways over the years,
often going by the name "Holy Grail Layout" when there are two additional columns.
Grid Layout makes this example trivial.
For example, take the following sketch of a page’s code and desired layout:

As an added bonus,
the columns will all be equal-height by default,
and the main content will be as wide as necessary to fill the screen.
Additionally,
this can then be combined with media queries to switch to an all-vertical layout on narrow screens:

In order to preserve the author’s intended ordering in all presentation modes,
authoring tools—including WYSIWYG editors as well as Web-based authoring aids—must reorder the underlying document source
and not use order or grid-placement properties to perform reordering
unless the author has explicitly indicated that the underlying
document order (which determines speech and navigation order) should be out-of-sync with the visual order.

For example, a tool might offer both drag-and-drop arrangement of grid items
as well as handling of media queries for alternate layouts per screen size range.

Since most of the time, reordering should affect all screen ranges
as well as navigation and speech order,
the tool would match the resulting drag-and-drop visual arrangement
by simultaneously reordering the DOM layer.
In some cases, however, the author may want different visual arrangements per screen size.
The tool could offer this functionality
by using the grid-placement properties together with media queries,
but also tie the smallest screen size’s arrangement to the underlying DOM order
(since this is most likely to be a logical linear presentation order)
while using grid-placement properties to rearrange the visual presentation in other size ranges.

This tool would be conformant, whereas a tool that only ever used
the grid-placement properties to handle drag-and-drop grid rearrangement
(however convenient it might be to implement it that way)
would be non-conformant.

A grid container establishes a new grid formatting context for its contents.
This is the same as establishing a block formatting context,
except that grid layout is used instead of block layout:
floats do not intrude into the grid container,
and the grid container’s margins do not collapse with the margins of its contents.
The contents of a grid container are laid out into a grid,
with grid lines forming the boundaries of each grid items’ containing block.
The overflow property applies to grid containers.

Grid containers are not block containers,
and so some properties that were designed with the assumption of block layout
don’t apply in the context of grid layout.
In particular:

the column-* properties in the Multi-column Layout module [CSS3COL] have no effect on a grid container.

5.3. Clamping Overly Large Grids

Since memory is limited,
UAs may clamp the possible size of the grid to be within a UA-defined limit,
dropping all lines outside that limit.
If a grid item is placed outside this limit,
its grid area must be clamped to within this limited grid.

To clamp a grid area:

If the grid area would span outside the limited grid,
its span is clamped to the last line of the limited grid.

If the grid area would be placed completely outside the limited grid,
its span must be truncated to 1
and the area repositioned into the last grid track on that side of the grid.

For example, if a UA only supported grids with at most 1000 tracks in each dimension,
the following placement properties:

Note: inter-element white space disappears:
it does not become its own grid item,
even though inter-element text does get wrapped in an anonymous grid item.

Note: The box of a anonymous item is unstyleable,
since there is no element to assign style rules to.
Its contents will however inherit styles (such as font settings) from the grid container.

6.1. Grid Item Display

A grid item establishes a new formatting context for its contents.
The type of this formatting context is determined by its display value, as usual.
However, grid items are grid-level boxes, not block-level boxes:
they participate in their container’s grid formatting context,
not in a block formatting context.

Note: Some values of display normally trigger the creation of anonymous boxes around the original box.
If such a box is a grid item,
it is blockified first,
and so anonymous box creation will not happen.
For example, two contiguous grid items with display: table-cell will become two separate display: blockgrid items,
instead of being wrapped into a single anonymous table.

Items with an intrinsic ratio follow the same rules,
except that in the case of a normal alignment value,
an auto size for the grid item is sized as for align-self: start (consistent with the width calculation rules for block-level replaced elements in CSS2.1 § 10.3.4).

The following informative table summarizes the automatic sizing of grid items:

6.4. Grid Item Margins and Paddings

As adjacent grid items are independently contained
within the containing block formed by their grid areas,
the margins of adjacent grid items do not collapse.

Percentage margins and paddings on grid items can be resolved against either:

their own axis (left/right percentages resolve against width, top/bottom resolve against height), or,

the inline axis (left/right/top/bottom percentages all resolve against width)

A User Agent must choose one of these two behaviors.

Note: This variance sucks, but it accurately captures the current state of the world
(no consensus among implementations, and no consensus within the CSSWG).
It is the CSSWG’s intention that browsers will converge on one of the behaviors,
at which time the spec will be amended to require that.

Authors should avoid using percentages in paddings or margins on grid items entirely,
as they will get different behavior in different browsers.

Auto margins expand to absorb extra space in the corresponding dimension,
and can therefore be used for alignment.

Grid items can overlap when they are positioned into intersecting grid areas,
or even when positioned in non-intersecting areas because of negative margins or positioning.
The painting order of grid items is exactly the same as inline blocks [CSS21],
except that order-modified document order is used in place of raw document order,
and z-index values other than auto create a stacking context even if position is static.
Thus the z-index property can easily be used to control the z-axis order of grid items.

Note: Descendants that are positioned outside a grid item still participate in any stacking context established by the grid item.

The following diagram shows several overlapping grid items,
with a combination of implicit source order
and explicit z-index used to control their stacking order.
Drawing order controlled by z-index and source order.

Note that while a content-based minimum size is often appropriate,
and helps prevent content from overlapping or spilling outside its container,
in some cases it is not:

In particular, if grid layout is being used for a major content area of a document,
it is better to set an explicit font-relative minimum width such as min-width: 12em.
A content-based minimum width could result in a large table or large image
stretching the size of the entire content area, potentially into an overflow zone,
and thereby making lines of text needlessly long and hard to read.

Note also, when content-based sizing is used on an item with large amounts of content,
the layout engine must traverse all of this content before finding its minimum size,
whereas if the author sets an explicit minimum, this is not necessary.
(For items with small amounts of content, however,
this traversal is trivial and therefore not a performance concern.)

Specifies the track list as a series of track sizing functions and line names.
Each track sizing function can be specified as a length,
a percentage of the grid container’s size,
a measurement of the contents occupying the column or row,
or a fraction of the free space in the grid.
It can also be specified as a range using the minmax() notation,
which can combine any of the previously mentioned mechanisms
to specify separate min and max track sizing functions for the column or row.

A non-negative dimension with the unit fr specifying the track’s flex factor.
Each <flex>-sized track takes a share of the remaining space in proportion to its flex factor.
See Flexible Lengths for more details.

Defines a size range
greater than or equal to min and less than or equal to max.
If max < min,
then max is ignored and minmax(min,max) is treated as min.
As a maximum, a <flex> value sets the track’s flex factor;
it is invalid as a minimum.

Represents the formula min(max-content, max(auto, argument)),
which is calculated similar to auto (i.e. minmax(auto, max-content)),
except that the track size is clamped at argument if it is greater than the auto minimum.

When auto-fill is given as the repetition number,
if the grid container has a definite size or max size in the relevant axis,
then the number of repetitions is the largest possible positive integer
that does not cause the grid to overflow its grid container (treating each track as its max track sizing function if that is definite or as its minimum track sizing function otherwise,
and taking grid-gap into account);
if any number of repetitions would overflow,
then 1 repetition.
Otherwise, if the grid container has a definite min size in the relevant axis,
the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement.
Otherwise, the specified track list repeats only once.

For example, the following code will create
as many 25-character columns as will fit into the window width.
If there is any remaining space,
it will be distributed among the 25-character columns.

The auto-fit keyword behaves the same as auto-fill,
except that after grid item placement any empty repeated tracks are collapsed.
An empty track is one with no in-flow grid items placed into or spanning across it.
(This can result in all tracks being collapsed,
if they’re all empty.)

The distribution of free space occurs after all non-flexible track sizing functions have reached their maximum.
The total size of such rows or columns is subtracted from the available space, yielding the free space,
which is then divided among the flex-sized rows and columns in proportion to their flex factor.

Each column or row’s share of the free space can be computed as the column or row’s <flex> * <free space> / <sum of all flex factors>.

Note: If the sum of the flex factors is less than 1,
they’ll take up only a corresponding fraction of the free space,
rather than expanding to fill the entire thing.
This is similar to how Flexbox [CSS-FLEXBOX-1] acts when the sum of the flex values is less than 1.

When the available space is infinite
(which happens when the grid container’s width or height is indefinite),
flex-sized grid tracks are sized to their contents while retaining their respective proportions.
The used size of each flex-sized grid track is computed by
determining the max-content size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical 1fr size”.
The maximum of those is used as the resolved 1fr length (the flex fraction),
which is then multiplied by each grid track’s flex factor to determine its final size.

Note: In general, resolved values are the computed values,
except for a small list of legacy 2.1 properties.
However, compatibility with early implementations of this module
requires us to define grid-template-rows and grid-template-columns as returning used values.

A row is created for every separate string listed for the grid-template-areas property,
and a column is created for each cell in the string,
when parsed as follows:

Tokenize the string into a list of the following tokens,
using longest-match semantics:

A sequence of name code points,
representing a named cell token with a name consisting of its code points.

A sequence of one or more "." (U+002E FULL STOP),
representing a null cell token.

A sequence of whitespace,
representing nothing
(do not produce a token).

A sequence of any other characters,
representing a trash token.

Note: These rules can produce cell names that do not match the <ident> syntax,
such as "1st 2nd 3rd",
which requires escaping when referencing those areas by name in other properties,
like grid-row: \31st; to reference the area named 1st.

All strings must have the same number of columns,
or else the declaration is invalid.
If a named grid area spans multiple grid cells,
but those cells do not form a single filled-in rectangle,
the declaration is invalid.

Note: Non-rectangular or disconnected regions may be permitted in a future version of this module.

In this example, the grid-template-areas property is used to create a page layout
where areas are defined for header content (head),
navigational content (nav),
footer content (foot),
and main content (main).
Accordingly, the template creates three rows and two columns,
with four named grid areas.
The head area spans both columns and the first row of the grid.

These named lines behave just like any other named line,
except that they do not appear in the value of grid-template-rows/grid-template-columns.
Even if an explicit line of the same name is defined,
the implicit named lines are just more lines with the same name.

Note: Note that the repeat() function isn’t allowed in these track listings,
as the tracks are intended to visually line up one-to-one with the rows/columns in the “ASCII art”.

Note: The grid shorthand accepts the same syntax,
but also resets the implicit grid properties to their initial values.
Unless authors want those to cascade in separately,
it is therefore recommended to use grid instead of grid-template.

If multiple track sizes are given, the pattern is repeated as necessary
to find the size of the implicit tracks.
The first implicit grid track before the explicit grid receives the first specified size, and so on forwards;
and the last implicit grid track before the explicit grid receives the last specified size, and so on backwards.

If specified, the auto-placement algorithm uses a “dense” packing algorithm,
which attempts to fill in holes earlier in the grid if smaller items come up later.
This may cause items to appear out-of-order,
when doing so would fill in holes left by larger items.

If omitted, a “sparse” algorithm is used,
where the placement algorithm only ever moves “forward” in the grid when placing items,
never backtracking to fill holes.
This ensures that all of the auto-placed items appear “in order”,
even if this leaves holes that could have been filled by later items.

Note: A future level of this module is expected to add a value that flows auto-positioned items together into a single “default” cell.

In the following example, there are three columns, each auto-sized to their contents.
No rows are explicitly defined.
The grid-auto-flow property is row which instructs the grid to search across its three columns starting with the first row,
then the next,
adding rows as needed until sufficient space is located to accommodate the position of any auto-placed grid item.

Note: Note that you can only specify the explicit or the implicit grid properties in a single grid declaration.
The sub-properties you don’t specify are set to their initial value,
as normal for shorthands.
Also, the gutter properties are reset by this shorthand,
even though they can’t be set by it.

The grid-placement properties of the subgrid’s grid items are scoped to the lines covered by the subgrid.
E.g., numeric indices count starting from the first line of the subgrid
rather than the first line of the parent grid.

The subgrid itself lays out as an ordinary grid item in its parent grid,
but acts as if it was completely empty for sizing purposes.

The subgrid’s own grid items participate in the sizing of its parent grid and are aligned to it.
In this process, the sum of the subgrid’s margin, padding, and borders at each edge
are applied as an extra layer of margin to the items at those edges.

For example, if we have a 3×3 grid with the following tracks:

#parent-grid { grid-template-columns: 300px auto 300px; }

If a subgrid covers the last two tracks,
its first two columns correspond to the parent grid’s last two columns,
and any items positioned into those tracks participate in sizing the parent grid.
Specifically, an item positioned in the first track of the subgrid
influences the auto-sizing of the parent grid’s middle track.

If there are multiple lines of the same name,
they effectively establish a named set of grid lines,
which can be exclusively indexed by filtering the placement by name:

.six {
grid-row: text 5 / text 7;
/* Span between the 5th and 7th lines named "text". */
grid-row: text 5 / span text 2;
/* Same as above - start at the 5th line named "text",
then span across two more "text" lines, to the 7th. */
}

9.1.4. Auto Placement

A grid item can be automatically placed into the next available empty grid cell,
growing the grid if there’s no space left.

.eight {
grid-area: auto; /* Initial value */
}

This can be used, for example, to list a number of sale items on a catalog site
in a grid pattern.

Auto-placement can be combined with an explicit span,
if the item should take up more than one cell:

Note: By default, the auto-placement algorithm looks linearly through the grid without backtracking;
if it has to skip some empty spaces to place a larger item,
it will not return to fill those spaces.
To change this behavior,
specify the dense keyword in grid-auto-flow.

9.2. Grid Item Placement vs. Source Order

“With great power comes great responsibility.”

The abilities of the grid-placement properties allow content to be freely arranged and reordered within the grid,
such that the visual presentation can be largely disjoint
from the underlying document source order.
These abilities allow the author great freedom
in tailoring the rendering to different devices
and modes of presentation
e.g. using media queries.
However they are not a substitute for correct source ordering.

Correct source order is important for speech,
for sequential navigation (such as keyboard navigation),
and non-CSS UAs such as search engines, tactile browsers, etc.
Grid placement only affects the visual presentation!
This allows authors to optimize the document source for
non-CSS/non-visual interaction modes,
and use grid placement techniques to further manipulate the visual presentation
so as to leave that source order intact.

If a name is given as a <custom-ident>,
only lines with that name are counted.
If not enough lines with that name exist,
all implicit grid lines are assumed to have that name for the purpose of finding this position.

If a name is given as a <custom-ident>,
only lines with that name are counted.
If not enough lines with that name exist,
all implicit grid lines on the side of the explicit grid corresponding to the search direction
are assumed to have that name for the purpose of counting this span.

Its column-start edge must be the first "foo" line it can find startward of that.
There is no "foo" line in the grid, though,
so the only possibility is a line in the implicit grid.
Line 3 is not a candidate, because it’s on the endward side of the explicit grid,
while the grid-column-start span forces it to search startward.
So, the only option is for the implicit grid to generate a line on the startward side of the explicit grid.

An illustration of the result.

If the <integer> is omitted, it defaults to 1.
Negative integers or zero are invalid.

Note: The resolution order for this shorthand is row-start/column-start/row-end/column-end,
which goes CCW for LTR pages,
the opposite direction of the related 4-edge properties using physical directions, like margin.

To aid in clarity,
this algorithm is written with the assumption that grid-auto-flow has row specified.
If it is instead set to column,
swap all mentions of rows and columns, inline and block, etc. in this algorithm.

Set the column-start line of its placement to the earliest (smallest positive index) line index
that ensures this item’s grid area will not overlap any occupied grid cells
and that is past any grid items previously placed in this row by this step.

Among all the items with a definite column position (explicitly positioned items, items positioned in the previous step, and items not yet positioned but with a definite column)
add columns to the beginning and end of the implicit grid as necessary to accomodate those items.

The number of columns needed is 6.
The explicit grid provides its 5 columns
(from grid-template-columns)
with lines number 1 through 6,
but #grid-item’s column position means it ends on line 7,
which requires an additional column added to the end of the implicit grid.

Position the remaining grid items.

The auto-placement cursor defines the current “insertion point” in the grid,
specified as a pair of row and column grid lines.
Initially the auto-placement cursor is set to the start-most row and column lines in the implicit grid.

Increment the column position of the auto-placement cursor until either this item’s grid area does not overlap any occupied grid cells,
or the cursor’s column position,
plus the item’s column span,
overflow the number of columns in the implicit grid,
as determined earlier in this algorithm.

If a non-overlapping position was found in the previous step,
set the item’s row-start and column-start lines to the cursor’s position.
Otherwise,
increment the auto-placement cursor’s row position
(creating new rows in the implicit grid as necessary),
set its column position to the start-most column line in the implicit grid,
and return to the previous step.

Set the cursor’s row and column positions to start-most row and column lines in the implicit grid.

Increment the column position of the auto-placement cursor until either this item’s grid area does not overlap any occupied grid cells,
or the cursor’s column position,
plus the item’s column span,
overflow the number of columns in the implicit grid,
as determined earlier in this algorithm.

If a non-overlapping position was found in the previous step,
set the item’s row-start and column-start lines to the cursor’s position.
Otherwise,
increment the auto-placement cursor’s row position
(creating new rows in the implicit grid as necessary),
reset its column position to the start-most column line in the implicit grid,
and return to the previous step.

Note: While absolutely-positioning an element to a grid container does allow it to align to that container’s grid lines,
such elements do not take up space or otherwise participate in the layout of the grid.

Instead of auto-placement, an auto value for a grid-placement property contributes a special line to the placement whose position is that of the corresponding padding edge of the grid container (the padding edge of the scrollable area, if the grid container overflows).
These lines become the first and last lines (0th and -0th) of the augmented grid used for positioning absolutely-positioned items.

Absolute positioning occurs after layout of the grid and its in-flow contents,
and does not contribute to the sizing of any grid tracks
or affect the size/configuration of the grid in any way.
If a grid-placement property refers to a non-existent line
either by explicitly specifying such a line or by spanning outside of the existing implicit grid,
it is instead treated as specifying auto (instead of creating new implicit grid lines).

Note: Note that this position is affected by the values of justify-self and align-self on the child,
and that, as in most other layout models,
the absolutely-positioned child has no effect on the size of the containing block
or layout of its contents.

These properties specify the gutters between grid rows and grid columns, respectively.
The effect is as though the affected grid lines acquired width:
the grid track between two grid lines is the space between the gutters that represent them.
For the purpose of track sizing,
each gutter is essentially treated as an extra, empty track of the specified size.
Negative values are invalid.

When a collapsed track’s gutters collapse,
they coincide exactly—the two gutters overlap so that their start and end edges coincide.
If one side of a collapsed track does not have a gutter
(e.g. if it is the first or last track of the implicit grid),
then collapsing its gutters results in no gutter
on either “side” of the collapsed track.

Note that alignment (unlike grid-gap spacing)
happens after the grid tracks are sized,
so if the track sizes are determined by the contents of the spanned item,
it will gain excess space in the alignment stage
to accommodate the alignment spacing.

11.6. Grid Container Baselines

The first (last) baselines of a grid container are determined as follows:

When calculating the baseline according to the above rules,
if the box contributing a baseline has an overflow value that allows scrolling,
the box must be treated as being in its initial scroll position
for the purpose of determining its baseline.

Once the size of each grid area is thus established,
the grid items are laid out into their respective containing blocks.

12.2. Track Sizing Terminology

min track sizing function

If the track was sized with a minmax() function,
this is the first argument to that function.
If the track was sized with a <flex> value or fit-content() function, auto.
Otherwise, the track’s sizing function.

max track sizing function

If the track was sized with a minmax() function,
this is the second argument to that function.
Otherwise, the track’s sizing function.
In all cases, treat auto and fit-content() as max-content,
except where specified otherwise for fit-content().

12.3. Track Sizing Algorithm

The remainder of this section is the track sizing algorithm,
which calculates from the min and max track sizing functions the used track size.
Each track has a base size,
a <length> which grows throughout the algorithm
and which will eventually be the track’s final size,
and a growth limit,
a <length> which provides a desired maximum size for the base size.
There are 4 steps:

12.5. Resolve Intrinsic Track Sizes

This step resolves intrinsic track sizing functions to absolute lengths.
First it resolves those sizes based on items that are contained wholly within a single track.
Then it gradually adds in the space requirements of items that span multiple tracks,
evenly distributing the extra space across those tracks
insofar as possible.

Note: There is no single way to satisfy these constraints
when items span across multiple tracks.
This algorithm embodies a number of heuristics
which have been seen to deliver good results on real-world use-cases,
such as the "game" examples earlier in this specification.
This algorithm may be updated in the future
to take into account more advanced heuristics as they are identified.

Size tracks to fit non-spanning items: For each track with an intrinsic track sizing function,
consider the items in it with a span of 1:

Otherwise,
set its base size to the maximum of its items’ min-size contributions:
the outer size that would result from assuming
an item’s min-width or min-height value
(whichever matches the relevant axis)
as its specified size
if its specified size (width or height, whichever matches the relevant axis) is auto,
or else the item’s min-content contribution.

Consider the following case:
Two "auto" tracks (i.e. minmax(min-content, max-content) minmax(min-content, max-content)).
Item 1 is in track 1, and has min-content = max-content = 10.
Item 2 spans tracks 1 and 2, and has min-content = 30, max-content = 100.
After resolving min-content/max-content for the first item, we have this.
track 1: base size = 10 growth limit = 10
track 2: base size = 0 growth limit = infinity
Then we resolve min-content/max-content for the second item.
Phase 1 sets the base size of track 2 to 20 so that the two tracks' base sizes sum to 30.
Phase 2 does nothing because there are no relevant tracks.
Phase 3 sets the growth limit of track 2 to 20 so that the two tracks' growth limits sum to 30.
In phase 4, we need to grow the sum of the growth limits by 70 to accommodate item 2.
Two options are:
1. Grow each track’s growth limit equally,
and end up with growth limits = [45, 55].
2. Grow only the second track’s growth limit,
and end up with growth limits = [10, 90].
By not considering the just-set growth limit as a constraint during space distribution
(i.e. by treating it as infinity),
we get the second result,
which we considered a better result because the first track remains sized exactly to the first item.

To distribute extra space by increasing the affected sizes of a set of tracks
as required by a set of intrinsic size contributions,

Maintain separately for each affected base size or growth limit an amount of planned increase.
(This prevents the size increases from becoming order-dependent.)

For each considered item,

Find the space to distribute: Subtract the corresponding size (base size or growth limit) of every spanned track
from the item’s size contribution to find the item’s remaining size contribution.
(For infinite growth limits, substitute the track’s base size.)
This is the space to distribute. Floor it at zero.

extra-space = max(0, size-contribution - ∑track-sizes)

Distribute space to base sizes up to growth limits: Distribute the space equally to the planned increase of each spanned track with an affected size,
freezing tracks as their planned size reaches their growth limits (and continuing to grow the unfrozen tracks as needed).

Update the tracks' affected sizes by folding in the calculated increase
so that the next round of space distribution will account for the increase.
(If the affected size is infinite,
set it to the track’s base size plus the calculated increase.)

Note: When this step is complete,
all intrinsic base sizes and growth limits will have been resolved to absolute lengths.

12.6. Maximize Tracks

If the free space is positive, distribute it equally to all tracks,
freezing tracks as they reach their growth limits (and continuing to grow the unfrozen tracks as needed).

13. Fragmenting Grid Layout

Grid containers can break across pages
between rows or columns
and inside items.
The break-* properties apply to grid containers
as normal for the formatting context in which they participate.
This section defines how they apply to grid items
and the contents of grid items.

When a grid container is continued after a break,
the space available to its grid items (in the block flow direction of the fragmentation context)
is reduced by the space consumed by grid container fragments on previous pages.
The space consumed by a grid container fragment is
the size of its content box on that page.
If as a result of this adjustment the available space becomes negative,
it is set to zero.

Aside from the rearrangement of items imposed by the previous point,
UAs should attempt to minimize distortation of the grid container
with respect to unfragmented flow.

13.1. Sample Fragmentation Algorithm

This section is non-normative.

This is a rough draft of one possible fragmentation algorithm,
and still needs to be severely cross-checked with the [CSS-FLEXBOX-1] algorithm for consistency.
Feedback is welcome; please reference the rules above instead as implementation guidance.

Layout the grid container using the values resolved in the previous step.

If a grid area’s size changes due to fragmentation (do not include items that
span rows in this decision), increase the grid row size as necessary for rows that either:

have a content min track sizing function.

are in a grid that does not have an explicit height and the grid row is flexible.

If the grid height is auto, the height of the grid should be the sum of the final
row sizes.

If a grid area overflows the grid container due to margins being collapsed during
fragmentation, extend the grid container to contain this grid area (this step is
necessary in order to avoid circular layout dependencies due to fragmentation).

If the grid’s height is specified, steps three and four may cause the grid rows to
overflow the grid.

14. Privacy and Security Considerations

Grid introduces no new privacy leaks,
or security considerations beyond "implement it correctly".

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:

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

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.

CR exit criteria

For this specification to be advanced to Proposed Recommendation,
there must be at least two independent, interoperable implementations
of each feature. Each feature may be implemented by a different set of
products, there is no requirement that all features be implemented by
a single product. For the purposes of this criterion, we define the
following terms:

independent

each implementation must be developed by a
different party and cannot share, reuse, or derive from code
used by another qualifying implementation. Sections of code that
have no bearing on the implementation of this specification are
exempt from this requirement.

interoperable

passing the respective test case(s) in the
official CSS test suite, or, if the implementation is not a Web
browser, an equivalent test. Every relevant test in the test
suite should have an equivalent test created if such a user
agent (UA) is to be used to claim interoperability. In addition
if such a UA is to be used to claim interoperability, then there
must one or more additional UAs which can also pass those
equivalent tests in the same way for the purpose of
interoperability. The equivalent tests must be made publicly
available for the purposes of peer review.

implementation

a user agent which:

implements the specification.

is available to the general public. The implementation may
be a shipping product or other publicly available version
(i.e., beta version, preview release, or "nightly build").
Non-shipping product releases must have implemented the
feature(s) for a period of at least one month in order to
demonstrate stability.

is not experimental (i.e., a version specifically designed
to pass the test suite and is not intended for normal usage
going forward).

The specification will remain Candidate Recommendation for at least
six months.