GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing drafts.csswg.org — CSS Grid Layout Module Level 2 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. IntroductionThis 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 following grid layout example shows how an author might achieve all the sizing, placement, and alignment rules declaratively.
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.
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 DefinitionsThis 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. OverviewThis 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. 2.1. Declaring the GridThe 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
Below are some examples of grid declarations:
2.2. Placing ItemsThe 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
Below are some examples of grid placement declarations
using the grid-area shorthand:
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 GridOnce 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
The following example justifies all columns
by distributing any extra space between them,
and centers the grid in the grid container
when it is smaller than 100vh.
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 TerminologyIn 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 LinesGrid 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.
The following two examples both create three column grid lines and four row grid lines.
This first example demonstrates how an author would position a grid item using grid line numbers: #grid This second example uses explicitly named grid lines:
3.2. Grid Tracks and CellsGrid 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.
#grid {
display: grid;
grid-template-columns: 150px 1fr; /* two columns */
grid-template-rows: 50px 1fr 50px; /* three rows */
}
3.3. Grid AreasA 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 ItemsA 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.
For example, suppose we have a form consisting of a list of inputs with labels:
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 AccessibilityGrid 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. 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:
This layout can be easily achieved with grid layout: body 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. 5. Grid Containers5.1. Establishing Grid Containers: the grid and inline-grid display values
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:
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 ContainersNote 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:
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 OverflowThe 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 GridsSince 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:
For example, if a UA only supported grids with at most 1000 tracks in each dimension,
the following placement properties:
.grid-item Would end up being equivalent to: .grid-item 6. Grid ItemsLoosely 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:
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 DisplayUnless 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 SizingA 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:
The following informative table summarizes the automatic sizing of grid items:
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 propertyThe 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 Display 3 § 3.1 Reordering and Accessibility in [CSS-DISPLAY-3]. 6.4. Grid Item Margins and PaddingsAs 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 propertyGrid 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.
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.
<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 ItemsNote: 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:
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:
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.
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.) 7. Defining the Grid7.1. The Explicit GridThe 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
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:
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>? [ <fixed-size> | <fixed-repeat> ] ]* <line-names>? <explicit-track-list> = [ <line-names>? <track-size> ]+ <line-names>? <line-name-list> = [ <line-names> | <name-repeat> ]+ <track-size> = <track-breadth> | minmax( <inflexible-breadth> , <track-breadth> ) | fit-content( <length-percentage [0,∞]> ) <fixed-size> = <fixed-breadth> | minmax( <fixed-breadth> , <track-breadth> ) | minmax( <inflexible-breadth> , <fixed-breadth> ) <track-breadth> = <length-percentage [0,∞]> | <flex [0,∞]> | min-content | max-content | auto <inflexible-breadth> = <length-percentage [0,∞]> | min-content | max-content | auto <fixed-breadth> = <length-percentage [0,∞]> <line-names> = '[' <custom-ident>* ']' Where the component values are defined as follows… 7.2.1. Track Sizes
Given the following grid-template-columns declaration:
grid-template-columns: 100px 1fr max-content minmax(min-content, 1fr); Five grid lines are created:
If the non-flexible sizes (100px, max-content, and min-content) sum to larger than the grid container’s width, the final grid line will be a distance equal to their sum away from the start edge of the grid container (the 1fr sizes both resolve to 0). If the sum is less than the grid container’s width, the final grid line will be exactly at the end edge of the grid container. This is true in general whenever there’s at least one <flex> value among the grid track sizes.
Additional examples of valid grid track definitions:
/* examples of valid track definitions */ grid-template-rows: 1fr minmax(min-content, 1fr); grid-template-rows: 10px repeat(2, 1fr auto minmax(30%, 1fr)); grid-template-rows: calc(4em - 5px); Note: The size of the grid is not purely the sum of the track sizes, as row-gap, column-gap and justify-content, align-content can add additional space between tracks. 7.2.2. Naming Grid Lines: the [<custom-ident>*] syntaxWhile grid lines can always be referred to by their numerical index, line names can make the grid-placement properties easier to understand and maintain. Line names can be explicitly assigned with the grid-template-rows and grid-template-columns properties, or implicitly assigned by named grid areas with the grid-template-areas property.
For example,
the following code gives meaningful names to all of the lines in the grid.
Note that some of the lines have multiple names.
#grid {
display: grid;
grid-template-columns: [first nav-start] 150px [main-start] 1fr [last];
grid-template-rows: [first header-start] 50px [main-start] 1fr [footer-start] 50px [last];
}
A line name cannot be span or auto, i.e. the <custom-ident> in the <line-names> production excludes the keywords span and auto. 7.2.3. Repeating Rows and Columns: the repeat() notationThe repeat() notation represents a repeated fragment of the track list, allowing a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form.
This example shows two equivalent ways of writing the same grid definition.
Both declarations produce four “main” columns, each 250px wide,
surrounded by 10px “gutter” columns.
grid-template-columns: 10px [col-start] 250px [col-end]
10px [col-start] 250px [col-end]
10px [col-start] 250px [col-end]
10px [col-start] 250px [col-end] 10px;
/* same as above, except easier to write */
grid-template-columns: repeat(4, 10px [col-start] 250px [col-end]) 10px;
7.2.3.1. Syntax of repeat()The generic form of the repeat() syntax is, approximately, repeat( [ <integer [1,∞]> | auto-fill | auto-fit ] , <track-list> ) The first argument specifies the number of repetitions. The second argument is a track list, which is repeated that number of times. However, there are some restrictions:
Thus the precise syntax of the repeat() notation has several forms: <track-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <track-size> ]+ <line-names>? ) <auto-repeat> = repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? ) <fixed-repeat> = repeat( [ <integer [1,∞]> ] , [ <line-names>? <fixed-size> ]+ <line-names>? ) <name-repeat> = repeat( [ <integer [1,∞]> | auto-fill ], <line-names>+)
If a repeat() function that is not a <name-repeat> ends up placing two <line-names> adjacent to each other, the name lists are merged. For example, repeat(2, [a] 1fr [b]) is equivalent to [a] 1fr [b a] 1fr [b]. 7.2.3.2. Repeat-to-fill: auto-fill and auto-fit repetitionsOn a subgridded axis, 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). Otherwise on a standalone axis, when auto-fill is given as the repetition number, if the grid container has a definite preferred size or maximum size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow the content box of its grid container taking gap into account; if any number of repetitions would overflow, then 1 repetition. Otherwise, if the grid container has a definite minimum 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 this purpose, each track is treated as its max track sizing function if that is definite or else its min track sizing function if that is definite. If both are definite, floor the max track sizing function by the min track sizing function. If neither are definite, the number of repetitions is one.
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.
body {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(25ch, 1fr));
}
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.) A collapsed grid track is treated as having a fixed track sizing function of 0px, and the gutters on either side of it—including any space allotted through distributed alignment—collapse. For the purpose of finding the number of auto-repeated tracks in a standalone axis, the UA must floor the track size to a UA-specified value to avoid division by zero. It is suggested that this floor be 1px. 7.2.3.3. Interpolation/Combination of repeat()If two repeat() notations that have the same first argument (repetition count) and the same number of tracks in their second argument (the track listing), they are combined by combining each component of their computed track lists by computed value (just like combining a top-level track list). They otherwise combine discretely. 7.2.4. Flexible Lengths: the fr unitA flexible length or <flex> is a dimension with the fr unit, which represents a fraction of the leftover space in the grid container. Tracks sized with fr units are called flexible tracks as they flex in response to leftover space similar to how flex items with a zero base size fill space in a flex container. The distribution of leftover 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 leftover 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 leftover space can be computed as the column or row’s
<flex> values between 0fr and 1fr have a somewhat special behavior: when the sum of the flex factors is less than 1, they will take up less than 100% of the leftover space.A track’s <flex> value is effectively a request for some proportion of the leftover space, with 1fr meaning “100% of the leftover space”; then if the tracks in that axis are requesting more than 100% in total, the requests are rebalanced to keep the same ratio but use up exactly 100% of it. However, if the tracks request less than the full amount (such as three tracks that are each .25fr) then they’ll each get exactly what they request (25% of the leftover space to each, with the final 25% left unfilled). See § 12.7 Expand Flexible Tracks for the exact details of how leftover space is distributed. This pattern is required for continuous behavior as fr values approach zero (which means the tracks wants none of the leftover space). Without this, a 1fr track would take all of the leftover space; but so would a 0.1fr track, and a 0.01fr track, etc., until finally the value is small enough to underflow to zero and the track suddenly takes up none of the leftover space. With this behavior, the track instead gradually takes less of the leftover space as its flex factor shrinks below 1fr, smoothly transitioning to taking none of the leftover space at zero. Unless this “partial fill” behavior is specifically what’s desired, authors should stick to values ≥ 1; for example, using 1fr and 2fr is usually better than using .33fr and .67fr, as they’re more likely to behave as intended if tracks are added or removed. 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: <flex> values are not <length>s (nor are they compatible with <length>s, like some <percentage> values), so they cannot be represented in or combined with other unit types in calc() expressions. 7.2.5. Computed Value of a Track ListingThe computed track list of a non-subgrid axis is a list alternating between line name sets and track sections, with the first and last items being line name sets. A line name set is a (potentially empty) set of identifiers representing line names. A track section is either:
The computed track list of a subgrid axis is the subgrid keyword followed by a list of line name sets and computed repeat notations representing the line names specified for that axis. 7.2.6. Resolved Value of a Track ListingThe grid-template-rows and grid-template-columns properties are resolved value special case properties. [CSSOM] 7.2.6.1. Resolved Value of a Standalone Track ListingWhen an element generates a grid container box, the resolved value of its grid-template-rows or grid-template-columns property in a standalone axis is the used value, serialized with:
The first bullet point of the above list
means that implicit tracks get serialized
as part of grid-template-rows/etc.,
despite the fact that an author cannot
actually specify implicit track sizes in those properties!
So grid-template-rows and grid-template-columns values
might not round-trip correctly:
This is an accidental property of an early implementation that leaked into later implementations without much thought given to it. We intend to remove it from the spec, but not until after we’ve defined a CSSOM API for getting information about implicit tracks, as currently this is the only way to get that information and a number of pages rely on that. Otherwise, (e.g. when the element has display: none or is not a grid container) the resolved value is simply the computed value.
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. The CSS Working Group is considering whether to also return used values for the grid-placement properties and is looking for feedback, especially from implementors. See discussion. 7.2.6.2. Resolved Value of a Subgridded Track ListingWhen an element generates a grid container box that is a subgrid, the resolved value of the grid-template-rows and grid-template-columns properties represents the used number of columns, serialized as the subgrid keyword followed by a list representing each of its lines as a line name set of all the line’s names explicitly defined on the subgrid (not including those adopted from the parent grid), without using the repeat() notation.
For example,
when applied to a subgrid with grid-column: span 4,
each of the following grid-template-columns specified values
becomes the corresponding resolved values:
Note: This violates the general "shortest equivalent serialization" principle by serializing empty trailing line name sets, as the trailing line name sets provide potentially-useful information about how many tracks the subgrid is spanning. 7.3. Named Areas: the grid-template-areas property
This property specifies named grid areas, which are not associated with any particular grid item, but can be referenced from the grid-placement properties. The syntax of the grid-template-areas property also provides a visualization of the structure of the grid, making the overall layout of the grid container easier to understand. Values have the following meanings:
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.
#grid {
display: grid;
grid-template-areas: "head head"
"nav main"
"foot ...."
}
#grid > header { grid-area: head; }
#grid > nav { grid-area: nav; }
#grid > main { grid-area: main; }
#grid > footer { grid-area: foot; }
7.3.1. Serialization Of Template StringsWhen serializing either the specified or computed value of a <string> value of grid-template-areas, each null cell token is serialized as a single "." (U+002E FULL STOP), and consecutive cell tokens are separated by a single space (U+0020 SPACE), with all other white space elided. 7.3.2. Implicitly-Assigned Line NamesThe grid-template-areas property generates implicitly-assigned line names from the named grid areas in the template. For each named grid area foo, four implicitly-assigned line names are created: two named foo-start, naming the row-start and column-start lines of the named grid area, and two named foo-end, naming the row-end and column-end lines of the named grid area. These implicitly-assigned line names behave just like any other line names, except that they do not appear in the value of grid-template-rows/grid-template-columns. Even if an explicitly-assigned line name with the same name is defined, the implicitly-assigned line names are just more lines with the same name. 7.3.3. Implicitly-Named AreasSince a named grid area is referenced by the implicitly-assigned line names it produces, explicitly adding named lines of the same form (foo-start/foo-end) effectively creates a named grid area. Such implicitly-named areas do not appear in the value of grid-template-areas, but can still be referenced by the grid-placement properties. 7.4. Explicit Grid Shorthand: the grid-template property
The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows, and grid-template-areas in a single declaration. It has several distinct syntax forms:
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. 7.5. The Implicit GridThe grid-template-rows, grid-template-columns, and grid-template-areas properties define a fixed number of tracks that form the explicit grid. When grid items are positioned outside of these bounds, the grid container generates implicit grid tracks by adding implicit grid lines to the grid. These lines together with the explicit grid form the implicit grid. The grid-auto-rows and grid-auto-columns properties size these implicit grid tracks, as well as any explicit grid tracks created by grid-template-areas but not explicitly sized by grid-template-rows or grid-template-columns The grid-auto-flow property controls auto-placement of grid items without an explicit position. Once the explicit grid is filled (or if there is no explicit grid) auto-placement will also cause the generation of implicit grid tracks. The grid shorthand property can set the implicit grid properties (grid-auto-flow, grid-auto-rows, and grid-auto-columns) together with the explicit grid properties in a single declaration. 7.6. Implicit Track Sizing: the grid-auto-rows and grid-auto-columns properties
The grid-auto-columns and grid-auto-rows properties specify the size of tracks not assigned a size by grid-template-rows or grid-template-columns. If multiple track sizes are given, the pattern is repeated as necessary to find the size of the affected tracks. The first track after the last explicitly-sized track 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. Note: If a grid item is positioned into a row or column that is not explicitly declared by grid-template-rows/grid-template-columns and/or grid-template-areas, implicit grid tracks are created to hold it. This can happen either by explicitly positioning into a row or column that is out of range, or by the auto-placement algorithm creating additional rows or columns.
7.7. Automatic Placement: the grid-auto-flow property
Grid items that aren’t explicitly placed are automatically placed into an unoccupied space in the grid container by the auto-placement algorithm. grid-auto-flow controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid. See § 8.5 Grid Item Placement Algorithm for details on precisely how the auto-placement algorithm works.
Note: A future level of this module is expected to add a value that flows auto-positioned items together into a single “default” cell. Auto-placement takes grid items in order-modified document order.
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.
A form arranged using automatic placement. <style type="text/css">
form {
display: grid;
/* Define three columns, all content-sized,
and name the corresponding lines. */
grid-template-columns: [labels] auto [controls] auto [oversized] auto;
grid-auto-flow: row dense;
}
form > label {
/* Place all labels in the "labels" column and
automatically find the next available row. */
grid-column: labels;
grid-row: auto;
}
form > input, form > select {
/* Place all controls in the "controls" column and
automatically find the next available row. */
grid-column: controls;
grid-row: auto;
}
#department-block {
/* Auto place this item in the "oversized" column
in the first row where an area that spans three rows
won't overlap other explicitly placed items or areas
or any items automatically placed prior to this area. */
grid-column: oversized;
grid-row: span 3;
}
/* Place all the buttons of the form
in the explicitly defined grid area. */
#buttons {
grid-row: auto;
/* Ensure the button area spans the entire grid element
in the inline axis. */
grid-column: 1 / -1;
text-align: end;
}
</style>
<form>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname">
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname">
<label for="address">Address:</label>
<input type="text" id="address" name="address">
<label for="address2">Address 2:</label>
<input type="text" id="address2" name="address2">
<label for="city">City:</label>
<input type="text" id="city" name="city">
<label for="state">State:</label>
<select type="text" id="state" name="state">
<option value="WA">Washington</option>
</select>
<label for="zip">Zip:</label>
<input type="text" id="zip" name="zip">
<div id="department-block">
<label for="department">Department:</label>
<select id="department" name="department" multiple>
<option value="finance">Finance</option>
<option value="humanresources">Human Resources</option>
<option value="marketing">Marketing</option>
</select>
</div>
<div id="buttons">
<button id="cancel">Cancel</button>
<button id="back">Back</button>
<button id="next">Next</button>
</div>
</form>
7.8. Grid Definition Shorthand: the grid property
The grid property is a shorthand that sets all of the explicit grid properties (grid-template-rows, grid-template-columns, and grid-template-areas), and all the implicit grid properties (grid-auto-rows, grid-auto-columns, and grid-auto-flow), in a single declaration. (It does not reset the gutter properties.) Its syntax matches grid-template, plus an additional syntax form for defining auto-flow grids:
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.
In addition to accepting the grid-template shorthand syntax for setting up the explicit grid,
the grid shorthand can also easily set up parameters for an auto-formatted grid.
For example, grid: auto-flow 1fr / 100px; is equivalent to
grid-template: none / 100px; grid-auto-flow: row; grid-auto-rows: 1fr; grid-auto-columns: auto; Similarly, grid: none / auto-flow 1fr is equivalent to grid-template: none; grid-auto-flow: column; grid-auto-rows: auto; grid-auto-columns: 1fr; When serializing, if all the grid-auto-* longhands have their initial values, the grid-template syntax is used. 8. Placing Grid ItemsEvery grid item is associated with a grid area, a rectangular set of adjacent grid cells that the grid item occupies. This grid area defines the containing block for the grid item within which the self-alignment properties (justify-self and align-self) determine their actual position. The cells that a grid item occupies also influence the sizing of the grid’s rows and columns, defined in § 12 Grid Layout Algorithm. The location of a grid item’s grid area within the grid is defined by its placement, which consists of a grid position and a grid span:
The grid-placement properties—the longhands grid-row-start, grid-row-end, grid-column-start, grid-column-end, and their shorthands grid-row, grid-column, and grid-area—allow the author to specify a grid item’s placement by providing any (or none) of the following six pieces of information:
A definite value for any two of Start, End, and Span in a given dimension implies a definite value for the third. 8.1. Common Patterns for Grid PlacementThis section is informative. The grid-placement property longhands are organized into three shorthands:
8.1.1. Named AreasAn item can be placed into a named grid area (such as those produced by the template in grid-template-areas) by specifying the area’s name in grid-area: An item can also be partially aligned with a named grid area, with other edges aligned to some other line: .one {
grid-row-start: main;
/* Align the row-start edge to the start edge of the "main" named area. */
}
8.1.2. Numeric Indexes and SpansGrid items can be positioned and sized by number, which is particularly helpful for script-driven layouts: .two {
grid-row: 2; /* Place item in the second row. */
grid-column: 3; /* Place item in the third column. */
/* Equivalent to grid-area: 2 / 3; */
}
By default, a grid item has a span of 1. Different spans can be given explicitly: .three {
grid-row: 2 / span 5;
/* Starts in the 2nd row,
spans 5 rows down (ending in the 7th row). */
}
.four {
grid-row: span 5 / 7;
/* Ends in the 7th row,
spans 5 rows up (starting in the 2nd row). */
}
Note: Note that grid indexes are writing mode relative. For example, in a right-to-left language like Arabic, the first column is the rightmost column. 8.1.3. Named Lines and SpansInstead of counting lines by number, lines can be referenced by their line name: Note: Note that if a named grid area has the same name as a line name, the placement algorithm will prefer to use named grid area’s lines instead. 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. */
}
8.1.4. Auto PlacementA grid item can be automatically placed into the next available empty grid cell, growing the grid if there’s no space left. 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: Whether the auto-placement algorithm searches across and adds rows, or searches across and adds columns, is controlled by the grid-auto-flow property. 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. 8.2. Grid Item Placement vs. Source Order
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. 8.3. Line-based Placement: the grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties
<grid-line> = auto | <custom-ident> | [ [ <integer [-∞,-1]> | <integer [1,∞]> ] && <custom-ident>? ] | [ span && [ <integer [1,∞]> || <custom-ident> ] ] The grid-row-start, grid-column-start, grid-row-end, and grid-column-end properties determine a grid item’s size and location within the grid by contributing a line, a span, or nothing (automatic) to its grid placement, thereby specifying the inline-start, block-start, inline-end, and block-end edges of its grid area. Values have the following meanings:
In all the above productions, the <custom-ident> additionally excludes the keywords span and auto.
Given a single-row, 8-column grid and the following 9 named lines:
1 2 3 4 5 6 7 8 9 +--+--+--+--+--+--+--+--+ | | | | | | | | | A B C A B C A B C | | | | | | | | | +--+--+--+--+--+--+--+--+ The following declarations place the grid item between the lines indicated by index: grid-column-start: 4; grid-column-end: auto; /* Line 4 to line 5 */ grid-column-start: auto; grid-column-end: 6; /* Line 5 to line 6 */ grid-column-start: C; grid-column-end: C -1; /* Line 3 to line 9 */ grid-column-start: C; grid-column-end: span C; /* Line 3 to line 6 */ grid-column-start: span C; grid-column-end: C -1; /* Line 6 to line 9 */ grid-column-start: span C; grid-column-end: span C; /* Error: The end span is ignored, and an auto-placed item can't span to a named line. Equivalent to ''grid-column: span 1;''. */ grid-column-start: 5; grid-column-end: C -1; /* Line 5 to line 9 */ grid-column-start: 5; grid-column-end: span C; /* Line 5 to line 6 */ grid-column-start: 8; grid-column-end: 8; /* Error: line 8 to line 9 */ grid-column-start: B 2; grid-column-end: span 1; /* Line 5 to line 6 */ 8.3.1. Grid Placement Conflict HandlingIf the placement for a grid item contains two lines, and the start line is further end-ward than the end line, swap the two lines. If the start line is equal to the end line, remove the end line. If the placement contains two spans, remove the one contributed by the end grid-placement property. If the placement contains only a span for a named line, replace it with a span of 1. 8.4. Placement Shorthands: the grid-column, grid-row, and grid-area properties
The grid-row and grid-column properties are shorthands for grid-row-start/grid-row-end and grid-column-start/grid-column-end, respectively. If two <grid-line> values are specified, the grid-row-start/grid-column-start longhand is set to the value before the slash, and the grid-row-end/grid-column-end longhand is set to the value after the slash. When the second value is omitted, if the first value is a <custom-ident>, the grid-row-end/grid-column-end longhand is also set to that <custom-ident>; otherwise, it is set to auto.
The grid-area property is a shorthand for grid-row-start, grid-column-start, grid-row-end and grid-column-end. If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the fourth value. When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to that <custom-ident>; otherwise, it is set to auto. When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that <custom-ident>; otherwise, it is set to auto. When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to that value. Otherwise, it is set to auto. 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. 8.5. Grid Item Placement AlgorithmThe following grid item placement algorithm resolves automatic positions of grid items into definite positions, ensuring that every grid item has a well-defined grid area to lay out into. (Grid spans need no special resolution; if they’re not explicitly specified, they default to 1.) Note: This algorithm can result in the creation of new rows or columns in the implicit grid, if there is no room in the explicit grid to place an auto-positioned grid item. Every grid cell (in both the explicit and implicit grids) can be occupied or unoccupied. A cell is occupied if it’s covered by the grid area of a grid item with a definite grid position; otherwise, the cell is unoccupied. A cell’s occupied/unoccupied status can change during this algorithm. 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. Note: The auto-placement algorithm works with the grid items in order-modified document order, not their original document order.
9. SubgridsA subgrid behaves just like a normal grid container except that:
10. Absolute Positioning10.1. With a Grid Container as Containing BlockIf an absolutely positioned element’s containing block is generated by a grid container, the containing block corresponds to the grid area determined by its grid-placement properties. The offset properties (top/right/bottom/left) then indicate offsets inwards from the corresponding edges of this containing block, as normal. 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. .grid {
grid: 1fr 1fr 1fr 1fr / 10rem 10rem 10rem 10rem;
/* 4 equal-height rows filling the grid container,
4 columns of ''10rem'' each */
justify-content: center;
/* center the grid horizontally within the grid container */
position: relative;
/* Establish abspos containing block */
}
.abspos {
grid-row-start: 1; /* 1st grid row line = top of grid container */
grid-row-end: span 2; /* 3rd grid row line */
grid-column-start: 3; /* 3rd grid col line */
grid-column-end: auto; /* right padding edge */
/* Containing block covers the top right quadrant of the grid container */
position: absolute;
top: 70px;
bottom: 40px;
left: 100px;
right: 30px;
}
Note: Grids and the grid-placement properties are flow-relative, while the offset properties (left, right, top, and bottom) are physical, so if the direction or writing-mode properties change, the grid will transform to match, but the offsets won’t. 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. Note: Thus, by default, the absolutely-positioned box’s containing block will correspond to the padding edges of the grid container, as it does for block containers. 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: Remember that implicit lines are assumed to have all line names, so a referenced line might exist even though it is not explicitly named. If the placement only contains a grid span, replace it with the two auto lines in that axis. (This happens when both grid-placement properties in an axis contributed a span originally, and § 8.3.1 Grid Placement Conflict Handling caused the second span to be ignored.) 10.2. With a Grid Container as ParentAn absolutely-positioned child of a grid container is out-of-flow and not a grid item, and so does not affect the placement of other items or the sizing of the grid. The static position [CSS2] of an absolutely-positioned child of a grid container is determined as if it were the sole grid item in a grid area whose edges coincide with the content edges of the grid container. 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. 11. Alignment and SpacingAfter a grid container’s grid tracks have been sized, and the dimensions of all grid items are finalized, grid items can be aligned within their grid areas. Note: The grid items of subgrids participate in alignment, including baseline alignment, together with their parent grid’s items; see Subgrids (h). The margin properties can be used to align items in a manner similar to what margins can do in block layout. Grid items also respect the box alignment properties from the CSS Box Alignment Module [CSS-ALIGN-3], which allow easy keyword-based alignment of items in both the rows and columns. By default, grid items stretch to fill their grid area. However, if justify-self or align-self compute to a value other than stretch or margins are auto, grid items will auto-size to fit their contents. 11.1. Gutters: the row-gap, column-gap, and gap propertiesThe row-gap and column-gap properties (and their gap shorthand), when specified on a grid container, define the gutters between grid rows and grid columns. Their syntax is defined in CSS Box Alignment 3 § 8 Gaps Between Boxes. The effect of these properties is as though the affected grid lines acquired thickness: 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 treated as an extra, empty, fixed-size track of the specified size, which is spanned by any grid items that span across its corresponding grid line. Note: Additional spacing may be added between tracks due to justify-content/align-content. See § 12.1 Grid Sizing Algorithm. This space effectively increases the size of the gutters. If a grid is fragmented between tracks, the gutter spacing between those tracks must be suppressed. Note that gutters are suppressed even after forced breaks, unlike margins. Gutters only appear between tracks of the implicit grid; there is no gutter before the first track or after the last track. (In particular, there is no gutter between the first/last track of the implicit grid and the “auto” lines in the augmented grid.) 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. 11.2. Aligning with auto marginsAuto margins on grid items have an effect very similar to auto margins in block layout:
11.3. Inline-axis Alignment: the justify-self and justify-items propertiesGrid items can be aligned in the inline dimension by using the justify-self property on the grid item or justify-items property on the grid container, as defined in [CSS-ALIGN-3].
For example,
for an English document,
the inline axis is horizontal,
and so the justify-* properties align the grid items horizontally.
If baseline alignment is specified on a grid item whose size in that axis depends on the size of an intrinsically-sized track (whose size is therefore dependent on both the item’s size and baseline alignment, creating a cyclic dependency), that item does not participate in baseline alignment, and instead uses its fallback alignment as if that were originally specified. For this purpose, <flex> track sizes count as “intrinsically-sized” when the grid container has an indefinite size in the relevant axis. Note: Whether the fallback alignment is used or not does not change over the course of layout: if a cycle exists, it exists. 11.4. Block-axis Alignment: the align-self and align-items propertiesGrid items can also be aligned in the block dimension (perpendicular to the inline dimension) by using the align-self property on the grid item or align-items property on the grid container, as defined in [CSS-ALIGN-3]. If baseline alignment is specified on a grid item whose size in that axis depends on the size of an intrinsically-sized track (whose size is therefore dependent on both the item’s size and baseline alignment, creating a cyclic dependency), that item does not participate in baseline alignment, and instead uses its fallback alignment as if that were originally specified. For this purpose, <flex> track sizes count as “intrinsically-sized” when the grid container has an indefinite size in the relevant axis. 11.5. Aligning the Grid: the justify-content and align-content propertiesIf the grid’s outer edges do not correspond to the grid container’s content edges (for example, if no columns are flex-sized), the grid tracks are aligned within the content box according to the justify-content and align-content properties on the grid container.
For example, the following grid is centered vertically,
and aligned to the right edge of its grid container:
.grid {
display: grid;
grid: 12rem 12rem 12rem 12rem / 10rem 10rem 10rem 10rem;
justify-content: end;
align-content: center;
min-height: 60rem;
}
If there are no grid tracks (the explicit grid is empty, and no tracks were created in the implicit grid), the sole grid line in each axis is aligned with the start edge of the grid container. Note that certain values of justify-content and align-content can cause the tracks to be spaced apart (space-around, space-between, space-evenly) or to be resized (stretch). If the grid is fragmented between tracks, any such additional spacing between those tracks must be suppressed.
For example, in the following grid,
the spanning item’s grid area is increased to accommodate
the extra space assigned to the gutters due to alignment:
.wrapper {
display: grid;
/* 3-row / 4-column grid container */
grid: repeat(3, auto) / repeat(4, auto);
gap: 10px;
align-content: space-around;
justify-content: space-between;
}
.item1 { grid-column: 1 / 5; }
.item2 { grid-column: 1 / 3; grid-row: 2 / 4; }
.item3 { grid-column: 3 / 5; }
/* last two items auto-place into the last two grid cells */
Note that alignment (unlike 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 BaselinesThe first baseline set of a grid container is taken from the first available of:
For this purpose, any grid item that spans multiple tracks is ignored if it’s span does not start in the indicated track; except that for step 2, it’s ignored if its span does not end in the track. Last baselines are analogous (with “first”/“last” and “start”/“end” inverted). Grid-modified document order (grid order) is the order in which grid items are encountered when traversing the grid’s grid cells. If two items are encountered at the same time, they are taken in order-modified document order. 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. When determining the baseline of a table cell, a grid container provides a baseline just as a line box or table-row does. [CSS2] See CSS Writing Modes 3 § 4.1 Introduction to Baselines and CSS Box Alignment 3 § 9 Baseline Alignment Details for more information on baselines. 12. Grid Layout AlgorithmThis section defines the grid layout algorithm, which sizes the grid container, sizes and positions all the grid tracks, and lays out the grid items which have been placed into its grid areas.
12.1. Grid Sizing AlgorithmThis section defines the grid sizing algorithm, which determines the size of all grid tracks and, by extension, the entire grid. Each track has specified minimum and maximum sizing functions (which may be the same). Each sizing function is either:
The grid sizing algorithm defines how to resolve these sizing constraints into used track sizes.
Note: 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 drill down per axis into subgrids, rather than completing both axes as it recurses. Note this means that a subgrid establishing an orthogonal flow would have the order of its track sizing inverted compared to 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-C>
<grid-D></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 treats 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:
The grid sizing algorithm in this example would thus look like this:
12.2. Track Sizing Terminology
Note: Remember that gutters are treated as fixed-size tracks—tracks with their min and max sizing functions both set to the gutter’s used size—for the purpose of the grid sizing algorithm. Their widths need to be incorporated into the track sizing algorithm’s calculations accordingly. 12.3. Track Sizing AlgorithmThe 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 5 steps:
12.4. Initialize Track SizesInitialize each track’s base size and growth limit. For each track, if the track’s min track sizing function is:
For each track, if the track’s max track sizing function is:
In all cases, if the growth limit is less than the base size, increase the growth limit to match the base size. Note: Gutters are treated as empty fixed-size tracks for the purpose of the track sizing algorithm. 12.5. Resolve Intrinsic Track SizesThis 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: When this step is complete, all intrinsic base sizes and growth limits will have been resolved to absolute lengths. Note: Remember that fit-content() and auto max track sizing functions are treated the same as max-content except where explicitly specified otherwise.
Note: There is no single way to satisfy intrinsic sizing 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. 12.5.1. Distributing Extra Space Across Spanned Tracks
To distribute extra space,
perform the following steps,
with these inputs:
12.6. Maximize TracksIf the free space is positive, distribute it equally to the base sizes of all tracks, freezing tracks as they reach their growth limits (and continuing to grow the unfrozen tracks as needed). For the purpose of this step: if sizing the grid container under a max-content constraint, the free space is infinite; if sizing under a min-content constraint, the free space is zero. If this would cause the grid to be larger than the grid container’s inner size as limited by its max-width/height, then redo this step, treating the available grid space as equal to the grid container’s inner size when it’s sized to its max-width/height. 12.7. Expand Flexible TracksThis step sizes flexible tracks using the largest value it can assign to an fr without exceeding the available space. First, find the grid’s used flex fraction:
For each flexible track, if the product of the used flex fraction and the track’s flex factor is greater than the track’s base size, set its base size to that product. 12.7.1. Find the Size of an frThis algorithm finds the largest size that an fr unit can be without exceeding the target size. It must be called with a set of grid tracks and some quantity of space to fill.
12.8. Stretch auto TracksWhen the content-distribution property of the grid container is normal or stretch in this axis, this step expands tracks that have an auto max track sizing function by dividing any remaining positive, definite free space equally amongst them. If the free space is indefinite, but the grid container has a definite min-width/height, use that size to calculate the free space for this step instead. 13. Fragmenting Grid LayoutGrid 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. The following breaking rules refer to the fragmentation container as the “page”. The same rules apply in any other fragmentation context. (Substitute “page” with the appropriate fragmentation container type as needed.) See the CSS Fragmentation Module [CSS3-BREAK]. The exact layout of a fragmented grid container is not defined in this level of Grid Layout. However, breaks inside a grid container are subject to the following rules:
13.1. Sample Fragmentation AlgorithmThis 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.
If the grid’s height is specified, steps three and four may cause the grid rows to overflow the grid. 14. Privacy ConsiderationsGrid Layout introduces no new privacy leaks. 15. Security ConsiderationsGrid Layout introduces no new security considerations. 16. Changes16.1. Changes since the 18 December 2020 CR
16.2. Changes since the August 2020 CR
Changes since the December 2019 CSS Grid Layout Level 2 Working DraftNone, except the incorporation of the full text of CSS Grid level 1. See Changes during Working Draft for previous changes. 16.3. Additions Since Level 1The following features have been added since Level 1: 17. AcknowledgementsMany 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. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||