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 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.
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.
Grid Level 2 adds 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.
1.1. 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.
1.1.1. Adapting Layouts to Available Space
Grid layout can be used to intelligently resize elements within a webpage. The adjacent figures 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 game board.
The following grid layout example shows how an author might achieve all the sizing, placement, and alignment rules declaratively.
/** * Define the space for each grid item by declaring the grid * on the grid container . */ #grid{ /** * Two columns: * 1. the first sized to content, * 2. the second receives the remaining space * (but is never smaller than the minimum size of the board * or the game controls, which occupy this column [Figure 4]) * * Three rows: * 3. the first sized to content, * 4. the middle row receives the remaining space * (but is never smaller than the minimum height * of the board or stats areas) * 5. the last sized to content. */ display: grid; grid-template-columns : /* 1 */ auto/* 2 */ 1 fr ; grid-template-rows : /* 3 */ auto/* 4 */ 1 fr /* 5 */ auto; } /* Specify the position of each grid item using coordinates on * the 'grid-row' and 'grid-column' properties of each grid item . */ #title{ grid-column : 1 ; grid-row : 1 ; } #score{ grid-column : 1 ; grid-row : 3 ; } #stats{ grid-column : 1 ; grid-row : 2 ; align-self : start; } #board{ grid-column : 2 ; grid-row : 1 / span2 ; } #controls{ grid-column : 2 ; grid-row : 3 ; justify-self : center; }
< div id = "grid" > < div id = "title" > Game Title</ div > < div id = "score" > Score</ div > < div id = "stats" > Stats</ div > < div id = "board" > Board</ div > < div id = "controls" > Controls</ div > </ div >
Note: There are multiple ways to specify the structure of the grid and to position and size grid items, each optimized for different scenarios.
1.1.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 6 and 7). 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.
@media ( orientation: portrait) { #grid{ display : grid; /* The rows, columns and areas of the grid are defined visually * using the grid-template-areas property. Each string is a row, * and each word an area. The number of words in a string * determines the number of columns. Note the number of words * in each string must be identical. */ grid-template-areas:"title stats" "score stats" "board board" "ctrls ctrls" ; /* The way to size columns and rows can be assigned with the * grid-template-columns and grid-template-rows properties. */ grid-template-columns: auto1 fr ; grid-template-rows : auto auto1 fr auto; } } @media ( orientation: landscape) { #grid{ display : grid; /* Again the template property defines areas of the same name, * but this time positioned differently to better suit a * landscape orientation. */ grid-template-areas:"title board" "stats board" "score ctrls" ; grid-template-columns : auto1 fr ; grid-template-rows : auto1 fr auto; } } /* The grid-area property places a grid item into a named * area of the grid. */ #title{ grid-area : title} #score{ grid-area : score} #stats{ grid-area : stats} #board{ grid-area : board} #controls{ grid-area : ctrls}
< div id = "grid" > < div id = "title" > Game Title</ div > < div id = "score" > Score</ div > < div id = "stats" > Stats</ div > < div id = "board" > Board</ div > < div id = "controls" > Controls</ div > </ div >
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.
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. 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
- fixed, flexible, and content-based track sizing functions
- explicit item placement via forwards (positive) and backwards (negative) numerical grid coordinates, named grid lines, and named grid areas; automatic item placement into empty areas, including reordering with order
- space-sensitive track repetition and automatic addition of rows or columns to accommodate additional content
- control over alignment and spacing with margins, gutters, and the alignment properties
- the ability to overlap content and control layering with z-index
Grid containers can be nested or mixed with flex containers as necessary to create more complex layouts.
2.1. Declaring the Grid
The tracks (rows and columns) of the grid are declared and sized either explicitly through the explicit grid properties or are implicitly created when items are placed outside the explicit grid. The grid shorthand and its sub-properties define the parameters of the grid. § 7 Defining the Grid
-
The following declares a grid with four named areas:
H
,A
,B
, andF
. 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 { display: grid; 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.
main { display: grid; grid: repeat(auto-fill, 5em) / auto-flow 1fr; height: 100vh; } @media print { main { grid: auto-flow 1fr / repeat(auto-fill, 5em); } }
-
The following declares a grid with 5 evenly-sized columns
and three rows,
with the middle row taking up all remaining space
(and at least enough to fit its contents).
main { display: grid; grid: auto 1fr auto / repeat(5, 1fr); min-height: 100vh; }
2.2. Placing Items
The contents of the grid container are organized into individual grid items (analogous to flex items), which are then assigned to predefined areas in the grid. They can be explicitly placed using coordinates through the grid-placement properties or implicitly placed into empty areas using auto-placement. § 8 Placing Grid Items
grid-area: a; /* Place into named grid area “a” */ grid-area: auto; /* Auto-place into next empty area */ grid-area: 2 / 4; /* Place into row 2, column 4 */ grid-area: 1 / 3 / -1; /* Place into column 3, span all rows */ grid-area: header-start / sidebar-start / footer-end / sidebar-end; /* Place using named lines */
These are equivalent to the following grid-row + grid-column declarations:
grid-row: a; grid-column: a; grid-row: auto; grid-column: auto; grid-row: 2; grid-column: 4; grid-row: 1 / -1; grid-column: 3; grid-row: header-start / footer-end; grid-column: sidebar-start / sidebar-end;
They can further be decomposed into the grid-row-start/grid-row-end/grid-column-start/grid-column-end longhands, e.g.
grid-area: a; /* Equivalent to grid-row-start: a; grid-column-start: a; grid-row-end: a; grid-column-end: a; */ grid-area: 1 / 3 / -1; /* Equivalent to grid-row-start: 1; grid-column-start: 3; grid-row-end: -1; grid-column-end: auto; */
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.
The resulting sized grid is aligned within the grid container according to the grid container’s align-content and justify-content properties. § 11 Alignment and Spacing
main { display: grid; grid: auto-flow auto / repeat(auto-fill, 5em); min-height: 100vh; justify-content: space-between; align-content: safe center; }
Finally each grid item is sized and aligned within its assigned grid area, as specified by its own sizing [CSS2] and alignment properties [CSS-ALIGN-3].
3. Grid Layout Concepts and Terminology
In grid layout, the content of a grid container is laid out by positioning and aligning it into a grid. The grid is an intersecting set of horizontal and vertical grid lines that divides the grid container’s space into grid areas, into which grid items (representing the grid container’s content) can be placed. There are two sets of grid lines: one set defining columns that run along the block axis, and an orthogonal set defining rows along the inline axis. [CSS3-WRITING-MODES]
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.
This first example demonstrates how an author would position a grid item using grid line numbers:
#grid{ display : grid; grid-template-columns : 150 px 1 fr ; grid-template-rows : 50 px 1 fr 50 px ; } #item1{ grid-column : 2 ; grid-row-start : 1 ; grid-row-end : 4 ; }
This second example uses explicitly named grid lines:
/* equivalent layout to the prior example, but using named lines */ #grid{ display : grid; grid-template-columns : 150 px [ item1-start] 1 fr [ item1-end]; grid-template-rows : [ item1-start] 50 px 1 fr 50 px [ item1-end]; } #item1{ grid-column : item1-start / item1-end; grid-row : item1-start / item1-end; }
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.
#grid { display: grid; grid-template-columns: 150px 1fr; /* two columns */ grid-template-rows: 50px 1fr 50px; /* three rows */ }
3.3. Grid Areas
A grid area is the logical space used to lay out one or more grid items. A grid area consists of one or more adjacent grid cells. It is bound by four grid lines, one on each side of the grid area, and participates in the sizing of the grid tracks it intersects. A grid area can be named explicitly using the grid-template-areas property of the grid container, or referenced implicitly by its bounding grid lines. A grid item is assigned to a grid area using the grid-placement properties.
/* using the template syntax */ #grid { display: grid; grid-template-areas: ". a" "b a" ". a"; grid-template-columns: 150px 1fr; grid-template-rows: 50px 1fr 50px; height: 100vh; } #item1 { grid-area: a } #item2 { grid-area: b } #item3 { grid-area: b } /* Align items 2 and 3 at different points in the grid area "b". */ /* By default, grid items are stretched to fit their grid area */ /* and these items would layer one over the other. */ #item2 { align-self: start; } #item3 { justify-self: end; align-self: end; }
A grid item’s grid area forms the containing block into which it is laid out. Grid items placed into the same grid area do not directly affect each other’s layout. Indirectly, however, a grid item occupying a grid track with an intrinsic sizing function can affect the size of that track (and thus the positions of its bounding grid lines), which in turn can affect the position or size of another grid item.
3.4. Nested vs. Subgridded Items
A grid item can itself be a grid container by giving it display: grid. In the general case the layout of this nested grid’s contents will be independent of the layout of the parent grid it participates in.
However, in some cases it might be necessary for the contents of multiple grid items to align to each other. A nested grid can defer the definition of its rows and/or columns to its parent grid container, making it a subgrid. In this case, the grid items of the subgrid participate in sizing the parent grid, allowing the contents of both grids to align. See § 9 Subgrids.
A subgrid is established by the subgrid keyword of grid-template-rows or grid-template-columns, and can be subgridded in either axis or in both. A grid that has no subgridded axis is a standalone grid.
< 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; }
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 placement
do 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
[HTML]).
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.)
<!DOCTYPE html> < header > ...</ header > < main > ...</ main > < nav > ...</ nav > < aside > ...</ aside > < footer > ...</ footer >
This layout can be easily achieved with grid layout:
body{ display : grid; grid : "h h h" "a b c" "f f f" ; grid-template-columns : auto1 fr 20 % ; } main{ grid-area : b; min-width : 12 em ; } nav{ grid-area : a; /* auto min-width */ } aside{ grid-area : c; min-width : 12 em ; }
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:
@media all and( max-width:60 em ) { /* Too narrow to support three columns */ body{ display : block; } }
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.
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.
5. Grid Containers
5.1. Establishing Grid Containers: the grid and inline-grid display values
Name: | display |
---|---|
New values: | grid | inline-grid |
- grid
- This value causes an element to generate a grid container box that is block-level when placed in flow layout.
- inline-grid
- This value causes an element to generate a grid container box that is inline-level when placed in flow layout.
A grid container that is not a subgrid establishes an independent grid formatting context for its contents. This is the same as establishing an independent 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.
Unlike those of a regular nested grid, a subgrid’s contents participate in its parent grid formatting context; thus a subgrid does not establish an independent formatting context.
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:
- float and clear have no effect on a grid item. However, the float property still affects the computed value of display on children of a grid container, as this occurs before grid items are determined.
- vertical-align has no effect on a grid item.
- the ::first-line and ::first-letter pseudo-elements do not apply to grid containers, and grid containers do not contribute a first formatted line or first letter to their ancestors.
If an element’s specified display is inline-grid and the element is floated or absolutely positioned, the computed value of display is grid. The table in CSS 2.1 Chapter 9.7 is thus amended to contain an additional row, with inline-grid in the "Specified Value" column and grid in the "Computed Value" column.
5.2. Sizing Grid Containers
Note see [CSS-SIZING-3] for a definition of the terms in this section.
A grid container is sized using the rules of the formatting context in which it participates:
- As a block-level box in a block formatting context, it is sized like a block box that establishes a formatting context, with an auto inline size calculated as for non-replaced block boxes.
- As an inline-level box in an inline formatting context, it is sized as an atomic inline-level box (such as an inline-block).
In both inline and block formatting contexts, the grid container’s auto block size is its max-content size.
The block layout spec should probably define this, but it isn’t written yet.
The max-content size (min-content size) of a grid container is the sum of the grid container’s track sizes (including gutters) in the appropriate axis, when the grid is sized under a max-content constraint (min-content constraint).
5.3. Scrollable Grid Overflow
The overflow property applies to grid containers.
Just as it is included in intrinsic sizing (see § 5.2 Sizing Grid Containers), the grid is also included in a grid container’s scrollable overflow region.
Note: Beware the interaction with padding when the grid container is a scroll container: additional padding is defined to be added to the scrollable overflow rectangle as needed to enable place-content: end alignment of scrollable content. See CSS Overflow 3 § 2.2 Scrollable Overflow
5.4. Limiting Large Grids
Since memory is limited, UAs may clamp the possible size of the implicit grid to be within a UA-defined limit (which should accommodate lines in the range [-10000, 10000]), 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.
.grid-item{ grid-row : 500 /1500 ; grid-column : 2000 /3000 ; }
Would end up being equivalent to:
.grid-item{ grid-row : 500 /1001 ; grid-column : 1000 /1001 ; }
6. Grid Items
Loosely speaking, the grid items of a grid container are boxes representing its in-flow contents.
Each in-flow child of a grid container becomes a grid item, and each child text sequence is wrapped in an anonymous block container grid item. However, if the text sequence contains only white space (i.e. characters that can be affected by the white-space property) it is instead not rendered (just as if its text nodes were display:none).
Examples of grid items:
< div style = "display: grid" > <!-- grid item: block child --> < div id = "item1" > block</ div > <!-- grid item: floated element; floating is ignored --> < div id = "item2" style = "float: left;" > float</ div > <!-- grid item: anonymous block box around inline content --> anonymous item 3<!-- grid item: inline child --> < span > item 4<!-- grid items do not split around blocks --> < q style = "display: block" id = not-an-item > item 4</ q > item 4</ span > </ div >
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
Unless it is a subgrid, a grid item establishes an independent formatting context for its contents. 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.
If the computed display value of an element’s nearest ancestor element (skipping display:contents ancestors) is grid or inline-grid, the element’s own display value is blockified. (See CSS2.1§9.7 [CSS2] and CSS Display 3 § 2.7 Automatic Box Type Transformations for details on this type of display value conversion.)
Note: Blockification still occurs even when the grid or inline-grid element does not end up generating a grid container box, e.g. when it is replaced or in a display: none subtree.
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: block grid items, instead of being wrapped into a single anonymous table.
6.2. Grid Item Sizing
A grid item is sized within the containing block defined by its grid area.
Grid item calculations for automatic sizes in a given dimensions vary by their self-alignment values:
- normal
-
If the grid item has no preferred aspect ratio, and no natural size in the relevant axis (if it is a replaced element), the grid item is sized as for align-self: stretch.
Otherwise, the grid item is sized consistent with the size calculation rules for block-level elements for the corresponding axis. (See CSS 2 § 10 Visual formatting model details.)
- stretch
-
Use the inline size calculation rules for non-replaced boxes (defined in CSS 2 § 10.3.3 Block-level, non-replaced elements in normal flow), i.e. the stretch-fit size.
Note: This can distort the aspect ratio of an item with a preferred aspect ratio, if its size is also constrained in the other axis.
- all other values
-
Size the item as fit-content.
Alignment | Non-replaced Element Size | Replaced Element Size |
---|---|---|
normal | Fill grid area | Use natural size |
stretch | Fill grid area | Fill grid area |
start/center/etc. | fit-content sizing (like floats) | Use natural size |
Note: The auto value of min-width and min-height affects track sizing in the relevant axis similar to how it affects the main size of a flex item. See § 6.6 Automatic Minimum Size of Grid Items.
6.3. Reordered Grid Items: the order property
The order property also applies to grid items. It affects their auto-placement and painting order.
As with reordering flex items, the order property must only be used when the visual order needs to be out-of-sync with the speech and navigation order; otherwise the underlying document source should be reordered instead. See CSS Flexbox 1 § 5.4.1 Reordering and Accessibility in [CSS-FLEXBOX-1].
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, like those on block boxes, are resolved against the inline size of their containing block, e.g. left/right/top/bottom percentages all resolve against their containing block’s width in horizontal writing modes.
Auto margins expand to absorb extra space in the corresponding dimension, and can therefore be used for alignment. See § 11.2 Aligning with auto margins
6.5. Z-axis Ordering: the z-index property
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 [CSS2], 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 (behaving exactly as if position were relative). 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.
<style type="text/css"> #grid { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr } #A { grid-column: 1 / span 2; grid-row: 2; align-self: end; } #B { grid-column: 1; grid-row: 1; z-index: 10; } #C { grid-column: 2; grid-row: 1; align-self: start; margin-left: -20px; } #D { grid-column: 2; grid-row: 2; justify-self: end; align-self: start; } #E { grid-column: 1 / span 2; grid-row: 1 / span 2; z-index: 5; justify-self: center; align-self: center; } </style> <div id="grid"> <div id="A">A</div> <div id="B">B</div> <div id="C">C</div> <div id="D">D</div> <div id="E">E</div> </div>
6.6. Automatic Minimum Size of Grid Items
Note: Much of the sizing terminology used in this section (and throughout the rest of the specification) is defined in CSS Intrinsic and Extrinsic Sizing [CSS-SIZING-3].
To provide a more reasonable default minimum size for grid items, the used value of its automatic minimum size in a given axis is the content-based minimum size if all of the following are true:
-
its computed overflow is not a scrollable overflow value
-
it spans at least one track in that axis whose min track sizing function is auto
-
if it spans more than one track in that axis, none of those tracks are flexible
Otherwise, the automatic minimum size is zero, as usual.
Note: The content-based minimum size is a type of intrinsic size contribution, and thus the provisions in CSS Sizing 3 § 5.2 Intrinsic Contributions apply.
The content-based minimum size for a grid item in a given dimension is its specified size suggestion if it exists, otherwise its transferred size suggestion if that exists and the element is replaced, else its content size suggestion, see below. However, if in a given dimension the grid item spans only grid tracks that have a fixed max track sizing function, then its specified size suggestion and content size suggestion in that dimension (and its input from this dimension to the transferred size suggestion in the opposite dimension) are further clamped to less than or equal to the stretch fit into the grid area’s maximum size in that dimension, as represented by the sum of those grid tracks’ max track sizing functions plus any intervening fixed gutters.
In all cases, the size suggestion is additionally clamped by the maximum size in the affected axis, if it’s definite. If the item is a compressible replaced element, and has a definite preferred size or maximum size in the relevant axis, the size suggestion is capped by those sizes; for this purpose, any indefinite percentages in these sizes are resolved against zero (and considered definite).
Note: The argument to fit-content() does not clamp the content-based minimum size in the same way as a fixed max track sizing function.
The content size suggestion, specified size suggestion, and transferred size suggestion used in this calculation account for the relevant min/max/preferred size properties so that the content-based minimum size does not interfere with any author-provided constraints, and are defined below:
- specified size suggestion
- If the item’s preferred size in the relevant axis is definite, then the specified size suggestion is that size. It is otherwise undefined.
- transferred size suggestion
-
If the item has a preferred aspect ratio
and its preferred size in the opposite axis is definite,
then the transferred size suggestion is that size
(clamped by the opposite-axis minimum and maximum sizes if they are definite),
converted through the aspect ratio.
It is otherwise undefined.
If the item has a definite preferred size or maximum size in the relevant axis, the transferred size suggestion is capped by those sizes; for this purpose, any indefinite percentages in these sizes are resolved against zero (and considered definite).
- content size suggestion
- The content size suggestion is the min-content size in the relevant axis, clamped, if it has a preferred aspect ratio, by any definite opposite-axis minimum and maximum sizes converted through the aspect ratio.
For the purpose of calculating an intrinsic size of the box (e.g. the box’s min-content size), a content-based minimum size causes the box’s size in that axis to become indefinite (even if e.g. its width property specifies a definite size). Note this means that percentages calculated against this size will behave as auto.
For any purpose other than calculating intrinsic sizes, a content-based minimum size (unlike an explicit min-content/etc minimum size) does not force the box’s size to become indefinite. However, if a percentage resolved against the box’s size before this minimum was applied, it must be re-resolved against the new size after it is applied.
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.)
7. Defining the Grid
7.1. The Explicit Grid
The three properties grid-template-rows, grid-template-columns, and grid-template-areas together define the explicit grid of a grid container by specifying its explicit grid tracks. The final grid may end up larger due to grid items placed outside the explicit grid; in this case implicit tracks will be created, these implicit tracks will be sized by the grid-auto-rows and grid-auto-columns properties.
The size of the explicit grid is determined by the larger of the number of rows/columns defined by grid-template-areas and the number of rows/columns sized by grid-template-rows/grid-template-columns. Any rows/columns defined by grid-template-areas but not sized by grid-template-rows/grid-template-columns take their size from the grid-auto-rows/grid-auto-columns properties. If these properties don’t define any explicit tracks the explicit grid still contains one grid line in each axis.
Numeric indexes in the grid-placement properties count from the edges of the explicit grid. Positive indexes count from the start side (starting from 1 for the start-most explicit line), while negative indexes count from the end side (starting from -1 for the end-most explicit line).
The grid and grid-template properties are shorthands that can be used to set all three explicit grid properties (grid-template-rows, grid-template-columns, and grid-template-areas) at the same time. The grid shorthand also resets properties controlling the implicit grid, whereas the grid-template property leaves them unchanged.
7.2. Explicit Track Sizing: the grid-template-rows and grid-template-columns properties
Name: | grid-template-columns, grid-template-rows |
---|---|
Value: | none | <track-list> | <auto-track-list> | subgrid <line-name-list>? |
Initial: | none |
Applies to: | grid containers |
Inherited: | no |
Percentages: | refer to corresponding dimension of the content area |
Computed value: | the keyword none or a computed track list |
Canonical order: | per grammar |
Animation type: | if the list lengths match, by computed value type per item in the computed track list (see § 7.2.5 Computed Value of a Track Listing and § 7.2.3.3 Interpolation/Combination of repeat()); discrete otherwise |
These properties specify, as a space-separated track list, the line names and track sizing functions of the grid. The grid-template-columns property specifies the track list for the grid’s columns, while grid-template-rows specifies the track list for the grid’s rows.
Values have the following meanings:
- none
-
Indicates that no explicit grid tracks are created by this property
(though explicit grid tracks could still be created by grid-template-areas).
Note: In the absence of an explicit grid any rows/columns will be implicitly generated, and their size will be determined by the grid-auto-rows and grid-auto-columns properties.
- <track-list> | <auto-track-list>
- 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.
- subgrid <line-name-list>?
-
The subgrid value
indicates that the grid will adopt the spanned portion
of its parent grid in that axis
(the subgridded 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.
Essentially,
subgrids provide the ability to pass grid parameters down through nested elements,
and content-based sizing information back up to their parent grid.
The <line-name-list> argument allows local naming of the grid lines shared with the parent grid: if a <line-name-list> is given, the specified <line-names>s are assigned to the lines of the subgrid’s explicit grid, one per line, starting with line 1. Excess <line-names> are ignored.
If there is no parent grid, or if the grid container is otherwise forced to establish an independent formatting context (for example, due to layout containment [CSS-CONTAIN-2] or absolute positioning [CSS-POSITION-3]), the used value is the initial value, none, and the grid container is not a subgrid.
An axis that is not subgridded is a standalone axis.
The syntax of a track list is:
<track-list> = [ <line-names>? [ <track-size> | <track-repeat> ] ]+ <line-names>? <auto-track-list> = [ <line-names>? [ <fixed-size> | <fixed-repeat> ] ]* <line-names>? <auto-repeat> [ <line-names>