<pre class='metadata'>
Title: CSS Grid Layout Module Level 2
Shortname: css-grid
Level: 2
Status: CRD
Work Status: Testing
Group: csswg
TR: https://www.w3.org/TR/css-grid-2/
ED: https://drafts.csswg.org/css-grid-2/
Issue Tracking: CSSWG GitHub https://github.com/w3c/csswg-drafts/issues?q=is%3Aopen+is%3Aissue+label%3Acss-grid-2
Implementation Report: https://wpt.fyi/results/css/css-grid/subgrid
WPT Path Prefix: css/css-grid/
Editor: Tab Atkins Jr., Google, http://www.xanthir.com/contact/, w3cid 42199
Editor: Elika J. Etemad / fantasai, Apple, http://fantasai.inkedblade.net/contact, w3cid 35400
Editor: Rossen Atanassov, Microsoft, ratan@microsoft.com, w3cid 49885
Editor: Oriol Brufau, Igalia, obrufau@igalia.com, w3cid 108473

Abstract: This CSS module defines a two-dimensional grid-based layout system, optimized for user interface design. In the grid layout model, the children of a grid container can be positioned into arbitrary slots in a predefined flexible or fixed-size layout grid. Level 2 expands Grid by adding “subgrid” capabilities for nested grids to participate in the sizing of their parent grids.
Ignored Terms: auto, grid-*-start, grid-*-end, flex factor, flex factors, grid-auto-position
Ignored Vars: A, B, C, size-contribution, track-sizes, extra-space
Link Defaults: css2 (property) margin/min-height/max-height/min-width/max-width, css-align-3 (value) stretch/baseline, css-position-3 (property) left, css-position-3 (property) position, css-writing-modes-3 (dfn) start/end
Ignore MDN Failure: valdef-grid-template-columns-minmax
</pre>

<pre class=link-defaults>
spec:css-align-3;
	type:value;
		text:center; for:align-self;
		text:stretch; for:align-self
		text:stretch; for:align-content
		text:space-between; for:justify-content
		text:space-around; for:justify-content
	type:property; text:column-gap
	type:value; for:column-gap; text:normal
	type:dfn; text:alignment baseline
spec:css-break-3; type:dfn; text:fragment
spec:css-display-3;
	type:dfn; text:order-modified document order
	type:property; text:order
spec:css-flexbox-1;
	type:dfn;
		text:specified size
		text:content size
		text:transferred size
	type:value;
		text:flex
		text:inline-flex
spec:css-pseudo-4; type:selector;
	text:::first-line
	text:::first-letter
</pre>

<style>
.example {
	clear:both
}

.pseudo-code {
	font-family:monospace
}
.pseudo-code > ol {
	list-style-type:decimal
}
.pseudo-code > ol > li > ol {
	list-style-type:lower-latin
}
.pseudo-code > ol > li > ol > li > ol {
	list-style-type:lower-roman
}
.pseudo-code ul {
	list-style-type:disc
}

dd > p:nth-child(1) {
	margin-top:0
}

dd:last-child {
	margin-bottom: 0;
}

dl.phase {
	padding-left: .5em;
	border-left: .5em #e0e0e0 solid;
}
#grid-property-breakdown tr:nth-child(3) td {
	width: 25%;
	border-style: solid;
}
</style>

Issue: If you notice any inconsistencies between this Grid Layout Module
and the <a href="http://www.w3.org/TR/css-flexbox/">Flexible Box Layout Module</a>,
please report them to the CSSWG,
as this is likely an error.

<h2 id='intro'>
Introduction</h2>

	<em>This section is not normative.</em>

	Grid Layout is a layout model for CSS
	that has powerful abilities to control the sizing and positioning of boxes and their contents.
	Unlike <a href="http://www.w3.org/TR/css-flexbox-1/">Flexible Box Layout</a>, which is single-axis&ndash;oriented,
	Grid Layout is optimized for 2-dimensional layouts:
	those in which alignment of content is desired in both dimensions.

	<figure>
		<img src="images/flex-layout.png"
		     alt="An example of flex layout:
		     two rows of items,
		     the first being three items a third of the space each,
		     and the second being five items, a fifth of the space each.
		     There is therefore alignment along the “rows”, but not along the “columns”.">
		<figcaption>Representative Flex Layout Example</figcaption>
	</figure>

	<figure>
		<img src="images/grid-layout.png"
		     alt="An example of grid layout:
		     two rows of items,
		     the first being four items&mdash;the last of which spans both rows,
		     and the second being two items&mdash;the first of which spans the first two columns&mdash; plus the spanned item from the first row.">
		<figcaption>Representative Grid Layout Example</figcaption>
	</figure>

	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 <a href="http://www.w3.org/TR/css3-mediaqueries/">media queries</a> 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&ndash;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 [[#subgrids|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.

<h3 id='background'>
Background and Motivation</h3>

	<figure class="sidefigure">
		<img class="figure" alt="Image: Application layout example requiring horizontal and vertical alignment." src="images/basic-form.png">
		<figcaption>Application layout example requiring horizontal and vertical alignment.</figcaption>
	</figure>

	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 <a>grid areas</a> 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.

<h4 id='adapting-to-available-space'>
Adapting Layouts to Available Space</h4>

	<figure class="sidefigure">
			<img src="images/game-smaller.png"
				alt="Let us consider the layout of a game in two columns and three rows: the game title in the top left corner, the menu below it, and the score in the bottom left with the game board occupying the top and middle cells on the right followed by game controls filling the bottom left. The left column is sized to exactly fit its contents (the game title, menu items, and score), with the right column filling the remaining space.">

		<figcaption>Five grid items arranged according to content size and available space.</figcaption>
	</figure>

	<figure class="sidefigure">
			<img src="images/game-larger.png"
				alt="As more space becomes available in larger screens, the middle row / right column are allowed to expand to fill that space.">

		<figcaption>Growth in the grid due to an increase in available space.</figcaption>
	</figure>

	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:

	<ul>
		<li>
			The stats area always appears immediately under the game title.
		<li>
			The game board appears to the right of the stats and title.
		<li>
			The top of the game title and the game board should always align.
		<li>
			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.
		<li>
			The controls are centered under the game board.
		<li>
			The top of the score area is aligned to the top of the controls area.
		<li>
			The score area is beneath the stats area.
		<li>
			The score area is aligned to the controls beneath the game board.
	</ul>

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


	<div class="example">
		<pre class="lang-css">
		/**
		 * Define the space for each <a>grid item</a> by declaring the grid
		 * on the <a>grid container</a>.
		 */
		#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 */ 1fr;
			grid-template-rows:
				/* 3 */ auto
				/* 4 */ 1fr
				/* 5 */ auto;
		}

		/* Specify the position of each <a>grid item</a> using coordinates on
		 * the 'grid-row' and 'grid-column' properties of each <a>grid item</a>.
		 */
		#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 / span 2; }
		#controls { grid-column: 2; grid-row: 3; justify-self: center; }
		</pre>

		<pre class="lang-markup">
			&lt;div id="grid">
			  &lt;div id="title">Game Title&lt;/div>
			  &lt;div id="score">Score&lt;/div>
			  &lt;div id="stats">Stats&lt;/div>
			  &lt;div id="board">Board&lt;/div>
			  &lt;div id="controls">Controls&lt;/div>
			&lt;/div>
		</pre>
	</div>

	Note: There are multiple ways to specify the structure of the grid
	and to position and size <a>grid items</a>,
	each optimized for different scenarios.

<h4 id='source-independence'>
Source-Order Independence</h4>

	<figure class="sidefigure">
		<img alt="Image: An arrangement suitable for portrait orientation." src="images/game-portrait.png">

		<figcaption>An arrangement suitable for “portrait” orientation.</figcaption>
	</figure>

	<figure class="sidefigure">
		<img alt="Image: An arrangement suitable for landscape orientation." src="images/game-landscape.png">

		<figcaption>An arrangement suitable for “landscape“ orientation.</figcaption>
	</figure>

	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 <a>grid item</a>.
	This allows the author to avoid rewriting rules for <a>grid items</a>
	as the grid’s definition changes.

	<div class="example">
		<pre class="lang-css">
		@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: auto 1fr;
				grid-template-rows: auto auto 1fr 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: auto 1fr;
				grid-template-rows: auto 1fr 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 }
		</pre>
		<pre class="lang-markup">
		&lt;div id="grid">
			&lt;div id="title">Game Title&lt;/div>
			&lt;div id="score">Score&lt;/div>
			&lt;div id="stats">Stats&lt;/div>
			&lt;div id="board">Board&lt;/div>
			&lt;div id="controls">Controls&lt;/div>
		&lt;/div>
		</pre>
	</div>

	Note: The reordering capabilities of grid layout intentionally affect
	<em>only the visual rendering</em>,
	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.

	Advisement: 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.

<h3 id="values">
Value Definitions</h3>

	This specification follows the <a href="https://www.w3.org/TR/CSS2/about.html#property-defs">CSS property definition conventions</a> from [[!CSS2]]
	using the <a href="https://www.w3.org/TR/css-values-3/#value-defs">value definition syntax</a> from [[!CSS-VALUES-3]].
	Value types not defined in this specification are defined in CSS Values &amp; 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 <a>CSS-wide keywords</a> as their property value.
	For readability they have not been repeated explicitly.

<h2 id='overview'>
Overview</h2>

	<em>This section is not normative.</em>

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

	<ul>
		<li>
			fixed, flexible, and content-based [[#track-sizing|track sizing functions]]
		<li>
			[[#placement|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 <a section href="#order-property">reordering with <css>order</css></a>
		<li>
			space-sensitive track repetition
			and
			automatic addition of rows or columns to accommodate additional content
		<li>
			control over alignment and spacing with
			[[#auto-margins|margins]], <a>gutters</a>, and the <a href="http://www.w3.org/TR/css-align/">alignment properties</a>
		<li>
			the ability to overlap content and <a section href="#z-order">control layering with <css>z-index</css></a>
	</ul>

	<a>Grid containers</a> can be nested or mixed with <a>flex containers</a>
	as necessary to create more complex layouts.

<h3 id="overview-grid">
Declaring the Grid</h3>

	The <a>tracks</a> (<a>rows</a> and <a>columns</a>) of the <a>grid</a>
	are declared and sized
	either explicitly through the <a>explicit grid</a> properties
	or are implicitly created when items are placed outside the <a>explicit grid</a>.
	The 'grid' shorthand and its sub-properties define the parameters
	of the grid.
	[[#grid-definition]]

	<div class="example">
		Below are some examples of grid declarations:

		<ul>
			<li>
				The following declares a grid with four named areas:
				<code>H</code>, <code>A</code>, <code>B</code>,
				and <code>F</code>.
				The first column is sized to fit its contents (''grid-template-columns/auto''),
				and the second column takes up the remaining space (<a value lt=fr>1fr</a>).
				Rows default to ''grid-template-rows/auto'' (content-based) sizing;
				the last row is given a fixed size of ''30px''.
				<pre>
					main {
					  display: grid;
					  grid: "H    H "
					        "A    B "
					        "F    F " 30px
					  /     auto 1fr;
					}
				</pre>
			<li>
				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 (<a value lt=fr>1fr</a>).
				Since content overflowing to the right won't print,
				an alternate layout for printing adds rows instead.

				<pre>
					main {
					  display: grid;
					  grid: repeat(auto-fill, 5em) / auto-flow 1fr;
					  height: 100vh;
					}
					@media print {
					  main {
					    grid: auto-flow 1fr / repeat(auto-fill, 5em);
					  }
					}
				</pre>
			<li>
				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).

				<pre>
					main {
					  display: grid;
					  grid: auto 1fr auto / repeat(5, 1fr);
					  min-height: 100vh;
					}
				</pre>
		</ul>
	</div>

<h3 id="overview-placement">
Placing Items</h3>

	The contents of the <a>grid container</a> are organized into individual <a>grid items</a>
	(analogous to <a>flex items</a>),
	which are then assigned to predefined [=grid areas|areas=] in the <a>grid</a>.
	They can be explicitly placed using coordinates through the <a>grid-placement properties</a>
	or implicitly placed into empty areas using [=auto-placement=].
	[[#placement]]

	<div class="example">
		Below are some examples of grid placement declarations
		using the 'grid-area' shorthand:

		<pre>
			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            */
		</pre>

		These are equivalent to the following 'grid-row' + 'grid-column' declarations:

		<pre>
			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;
		</pre>

		They can further be decomposed into the 'grid-row-start'/'grid-row-end'/'grid-column-start'/'grid-column-end' longhands, e.g.
		<pre>
			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; */
		</pre>
	</div>

<h3 id="overview-sizing">
Sizing the Grid</h3>

	Once the <a>grid items</a> have been [[#placement|placed]],
	the sizes of the <a>grid tracks</a> (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 [[#grid-align|aligned]] within the <a>grid container</a>
	according to the <a>grid container</a>’s 'align-content' and 'justify-content' properties.
	[[#alignment]]

	<div class="example">
		The following example justifies all columns
		by distributing any extra space between them,
		and centers the grid in the <a>grid container</a>
		when it is smaller than 100vh.

		<pre>
			main {
				display: grid;
				grid: auto-flow auto / repeat(auto-fill, 5em);
				min-height: 100vh;
				justify-content: space-between;
				align-content: safe center;
			}
		</pre>
	</div>

	Finally each <a>grid item</a> is sized and aligned within its assigned <a>grid area</a>,
	as specified by its own <a href="https://www.w3.org/TR/CSS2/visudet.html">sizing</a> [[!CSS2]] and <a lt="box alignment properties">alignment properties</a> [[!CSS-ALIGN-3]].


<!--
 ██████   ███████  ██    ██  ██████  ████████ ████████  ████████  ██████
██    ██ ██     ██ ███   ██ ██    ██ ██       ██     ██    ██    ██    ██
██       ██     ██ ████  ██ ██       ██       ██     ██    ██    ██
██       ██     ██ ██ ██ ██ ██       ██████   ████████     ██     ██████
██       ██     ██ ██  ████ ██       ██       ██           ██          ██
██    ██ ██     ██ ██   ███ ██    ██ ██       ██           ██    ██    ██
 ██████   ███████  ██    ██  ██████  ████████ ██           ██     ██████
-->

<h2 id='grid-concepts'>
Grid Layout Concepts and Terminology</h2>

	In <dfn export>grid layout</dfn>,
	the content of a <a>grid container</a> is laid out
	by positioning and aligning it into a <a>grid</a>.
	The <dfn export>grid</dfn> is an intersecting set of horizontal and vertical <a>grid lines</a>
	that divides the <a>grid container</a>’s space into <a>grid areas</a>,
	into which <a>grid items</a> (representing the <a>grid container</a>’s content) can be placed.
	There are two sets of <a>grid lines</a>:
	one set defining <dfn export lt="grid column" local-lt="column">columns</dfn>
	that run along the <a href="https://www.w3.org/TR/css3-writing-modes/#block-axis">block axis</a>,
	and an orthogonal set defining <dfn export lt="grid row" local-lt="row">rows</dfn>
	along the <a href="https://www.w3.org/TR/css3-writing-modes/#inline-axis">inline axis</a>.
	[[!CSS3-WRITING-MODES]]

<!--
	<div class="figure">
		<img class="figure" alt="Image: A diagram illustrating the relationship between the Grid Element and its Tracks, Lines, Areas and Items." src="images/grid-concepts.png">
		<p class="caption">A diagram illustrating the relationship between the <a>grid container</a> and its tracks, lines, areas and items.
	</div>
-->

	<figure>
		<img class="figure" alt="Image: Grid Lines." src="images/grid-lines.png">
		<figcaption>Grid lines: Three in the block axis and four in the inline axis.</figcaption>
	</figure>

<h3 id="grid-line-concept">
Grid Lines</h3>

	<dfn id='grid-line' export lt='grid line|grid row line|grid column line'>Grid lines</dfn> are the horizontal and vertical dividing lines of the <a>grid</a>.
	A <a>grid line</a> exists on either side of a column or row.
	They can be referred to by numerical index,
	or by an author-specified name.
	A <a>grid item</a> references the <a>grid lines</a> to determine its position within the <a>grid</a>
	using the [[#placement|grid-placement properties]].

	<div class="example">
		The following two examples both create three column <a>grid lines</a> and four row <a>grid lines</a>.

		This first example demonstrates how an author would position a <a>grid item</a> using <a>grid line</a> numbers:
		<pre class="lang-css">
			#grid {
				display: grid;
				grid-template-columns: 150px 1fr;
				grid-template-rows: 50px 1fr 50px;
			}

			#item1 { grid-column: 2;
			         grid-row-start: 1; grid-row-end: 4; }
		</pre>

		This second example uses explicitly named <a>grid lines</a>:

		<pre class="lang-css">
			/* equivalent layout to the prior example, but using named lines */
			#grid {
				display: grid;
				grid-template-columns: 150px [item1-start] 1fr [item1-end];
				grid-template-rows: [item1-start] 50px 1fr 50px [item1-end];
			}

			#item1 {
				grid-column: item1-start / item1-end;
				grid-row: item1-start / item1-end;
			}
		</pre>
	</div>

<h3 id="grid-track-concept">
Grid Tracks and Cells</h3>

	<dfn export local-lt="track">Grid track</dfn> is a generic term for a <a>grid column</a> or <a>grid row</a>&mdash;in
	other words, it is the space between two adjacent <a>grid lines</a>.
	Each <a>grid track</a> is assigned a sizing function,
	which controls how wide or tall the column or row may grow,
	and thus how far apart its bounding <a>grid lines</a> are.
	Adjacent <a>grid tracks</a> can be separated by [[#gutters|gutters]]
	but are otherwise packed tightly.

	A <dfn export>grid cell</dfn> 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 <a>grid items</a>.

	<div class="example">
		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 <a>grid container</a> changes.
		If the used width of the <a>grid container</a> is 200px, then the second column is 50px wide.
		If the used width of the <a>grid container</a> is 100px, then the second column is 0px
		and any content positioned in the column will overflow the <a>grid container</a>.

		<pre>
				#grid {
					display: grid;
					grid-template-columns: 150px 1fr;  /* two columns */
					grid-template-rows: 50px 1fr 50px; /* three rows  */
				}
		</pre>
	</div>

<h3 id="grid-area-concept">
Grid Areas</h3>

	A <dfn export>grid area</dfn> is the logical space used to lay out one or more <a>grid items</a>.
	A <a>grid area</a> consists of one or more adjacent <a>grid cells</a>.
	It is bound by four <a>grid lines</a>, one on each side of the <a>grid area</a>,
	and participates in the sizing of the <a>grid tracks</a> it intersects.
	A <a>grid area</a> can be named explicitly using the 'grid-template-areas' property of the <a>grid container</a>,
	or referenced implicitly by its bounding <a>grid lines</a>.
	A <a>grid item</a> is assigned to a <a>grid area</a>
	using the [[#placement|grid-placement properties]].

	<div class="example">
		<pre>
			/* 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; }
		</pre>
	</div>

	A <a>grid item</a>’s <a>grid area</a> forms the containing block into which it is laid out.
	<a>Grid items</a> placed into the same <a>grid area</a> do not directly affect each other's layout.
	Indirectly, however, a <a>grid item</a> occupying a <a>grid track</a> with an <a>intrinsic sizing function</a>
	can affect the size of that track (and thus the positions of its bounding <a>grid lines</a>),
	which in turn can affect the position or size of another <a>grid item</a>.

<h3 id="subgrid-items">
Nested vs. Subgridded Items</h3>

	A <a>grid item</a> can itself be a <a>grid container</a> by giving it ''display: grid''.
	In the general case the layout of this <dfn>nested grid</dfn>’s contents
	will be independent of the layout of the <dfn>parent grid</dfn> it participates in.

	However, in some cases it might be necessary
	for the contents of multiple <a>grid items</a> 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 <dfn export>subgrid</dfn>.
	In this case, the <a>grid items</a> of the <a>subgrid</a>
	participate in sizing the [=parent grid=],
	allowing the contents of both grids to align.
	See [[#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 <dfn export>standalone grid</dfn>.

	<div class="example">
		For example, suppose we have a form consisting of a list of inputs with labels:

		<pre class="lang-html">
			&lt;ul>
				&lt;li>&lt;label>Name:&lt;/label> &lt;input name=fn>
				&lt;li>&lt;label>Address:&lt;/label> &lt;input name=address>
				&lt;li>&lt;label>Phone:&lt;/label> &lt;input name=phone>
			&lt;/ul>
		</pre>

		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:

		<pre>
			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;
			}
		</pre>
	</div>

<h2 id="order-accessibility">
Reordering and Accessibility</h2>

	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 <a>grid placement</a>
	<em>do not</em> affect ordering in non-visual media
	(such as <a href="https://www.w3.org/TR/css3-speech/">speech</a>).
	Likewise, rearranging grid items visually does not affect
	the default traversal order of sequential navigation modes
	(such as cycling through links, see e.g. <a href="https://html.spec.whatwg.org/multipage/interaction.html#attr-tabindex"><code>tabindex</code></a> [[HTML]]).

	Advisement:
	Authors <em>must</em> use 'order' and the <a>grid-placement properties</a>
	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.)

	<div class='example'>
		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:

		<div class='code-and-figure'>
			<div>
				<pre class="lang-markup">
					&lt;!DOCTYPE html>
					&lt;header>...&lt;/header>
					&lt;main>...&lt;/main>
					&lt;nav>...&lt;/nav>
					&lt;aside>...&lt;/aside>
					&lt;footer>...&lt;/footer>
				</pre>
			</div>
			<div><img src="images/grid-order-page.svg" width=400 height=360 alt="In this page the header is at the top and the footer at the bottom, but the main is in the center, flanked by the nav on the right and the aside on the left."></div>
		</div>

		This layout can be easily achieved with grid layout:

		<pre class="lang-css">
			body { display: grid;
			       grid: "h h h"
			             "a b c"
			             "f f f";
			       grid-template-columns: auto 1fr 20%; }
			main    { grid-area: b; min-width: 12em;     }
			nav     { grid-area: a; /* auto min-width */ }
			aside   { grid-area: c; min-width: 12em;     }
		</pre>

		As an added bonus,
		the columns will all be <a value for="align-self" lt="stretch">equal-height</a> 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:

		<pre class="lang-css">
			@media all and (max-width: 60em) {
				/* Too narrow to support three columns */
				body { display: block; }
			}
		</pre>
	</div>

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

	<div class="example">
		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 <a>grid-placement properties</a> 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 <a>grid-placement properties</a>
		to rearrange the visual presentation in other size ranges.

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

<!--
████████  ████  ██████  ████████  ██          ███    ██    ██  ██   ██████   ████████  ████ ████████
██     ██  ██  ██    ██ ██     ██ ██         ██ ██    ██  ██  ████ ██    ██  ██     ██  ██  ██     ██
██     ██  ██  ██       ██     ██ ██        ██   ██    ████    ██  ██        ██     ██  ██  ██     ██
██     ██  ██   ██████  ████████  ██       ██     ██    ██         ██   ████ ████████   ██  ██     ██
██     ██  ██        ██ ██        ██       █████████    ██     ██  ██    ██  ██   ██    ██  ██     ██
██     ██  ██  ██    ██ ██        ██       ██     ██    ██    ████ ██    ██  ██    ██   ██  ██     ██
████████  ████  ██████  ██        ████████ ██     ██    ██     ██   ██████   ██     ██ ████ ████████
-->

<h2 id="grid-model">
Grid Containers</h2>

<h3 id='grid-containers'>
Establishing Grid Containers: the ''display/grid'' and ''inline-grid'' 'display' values</h3>

	<div class="informative">
		<pre class="propdef partial">
		Name: display
		New values: grid | inline-grid
		</pre>
	</div>

	<dl dfn-for="display" dfn-type=value>
		<dt><dfn>grid</dfn>
		<dd>
			This value causes an element to generate a <a>grid container</a> box
			that is <a>block-level</a> when placed in <a>flow layout</a>.

		<dt><dfn>inline-grid</dfn>
		<dd>
			This value causes an element to generate a <a>grid container</a> box
			that is <a>inline-level</a> when placed in <a>flow layout</a>.
	</dl>

	A <dfn export>grid container</dfn> that is not a [=subgrid=] establishes
	an [=independent formatting context|independent=] <dfn export>grid formatting context</dfn>
	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 <a>grid container</a> are laid out into a <a>grid</a>,
	with <a>grid lines</a> forming the boundaries of each <a>grid items</a>’ containing block.

	Unlike those of a regular nested grid,
	a [=subgrid=]’s contents participate in its parent <a>grid formatting context</a>;
	thus a subgrid does not establish an <a>independent formatting context</a>.

	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:

	<ul>
		<li>
			'float' and 'clear' have no effect on a <a>grid item</a>.
			However, the 'float' property still affects the computed value of 'display' on children of a grid container,
			as this occurs <em>before</em> <a>grid items</a> are determined.

		<li>
			'vertical-align' has no effect on a grid item.

		<li>
			the ''::first-line'' and ''::first-letter'' pseudo-elements do not apply to <a>grid containers</a>,
			and <a>grid containers</a> do not contribute a first formatted line or first letter to their ancestors.
	</ul>

	If an element's specified 'display' is ''inline-grid''
	and the element is floated or absolutely positioned,
	the computed value of 'display' is <a value>grid</a>.
	The table in <a href="https://www.w3.org/TR/CSS2/visuren.html#dis-pos-flo">CSS 2.1 Chapter 9.7</a> is thus amended
	to contain an additional row,
	with ''inline-grid'' in the "Specified Value" column
	and ''grid'' in the "Computed Value" column.

<h3 id='intrinsic-sizes'>
Sizing Grid Containers</h3>

	Note see [[!CSS-SIZING-3]] for a definition of the terms in this section.

	A <a>grid container</a> is sized
	using the rules of the formatting context in which it participates:

	<ul>
		<li>
			As a <a>block-level</a> box in a <a>block formatting context</a>,
			it is sized like a <a>block box</a> that establishes a formatting context,
			with an ''auto'' <a>inline size</a> calculated as for non-replaced block boxes.
		<li>
			As an inline-level box in an <a>inline formatting context</a>,
			it is sized as an atomic inline-level box (such as an inline-block).
	</ul>

	In both inline and block formatting contexts,
	the <a>grid container</a>’s ''auto'' <a>block size</a> is its max-content size.

	<span class="note">The block layout spec should probably define this,
	but it isn't written yet.</span>

	The <a>max-content size</a> (<a>min-content size</a>) of a <a>grid container</a> is
	the sum of the <a>grid container’s</a> track sizes (including gutters)
	in the appropriate axis,
	when the grid is sized under a <a>max-content constraint</a> (<a>min-content constraint</a>).

<h3 id='overflow'>
Scrollable Grid Overflow</h3>

	The 'overflow' property applies to <a>grid containers</a>.

	Just as it is included in intrinsic sizing (see [[#intrinsic-sizes]]),
	the <a>grid</a> is also included
	in a <a>grid container</a>’s <a>scrollable overflow region</a>.

	Note: Beware the interaction with padding
	when the <a>grid container</a> is a <a>scroll container</a>:
	additional padding is defined to be added
	to the <a>scrollable overflow rectangle</a>
	as needed to enable ''place-content: end'' alignment of scrollable content.
	See [[css-overflow-3#scrollable]]

<!--
 ██████  ██          ███    ██     ██ ████████  ████ ██    ██  ██████
██    ██ ██         ██ ██   ███   ███ ██     ██  ██  ███   ██ ██    ██
██       ██        ██   ██  ████ ████ ██     ██  ██  ████  ██ ██
██       ██       ██     ██ ██ ███ ██ ████████   ██  ██ ██ ██ ██   ████
██       ██       █████████ ██     ██ ██         ██  ██  ████ ██    ██
██    ██ ██       ██     ██ ██     ██ ██         ██  ██   ███ ██    ██
 ██████  ████████ ██     ██ ██     ██ ██        ████ ██    ██  ██████
-->

<h3 id="overlarge-grids">
Limiting Large Grids</h3>

	Since memory is limited,
	UAs may clamp the possible size of the <a>implicit grid</a>
	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 <a>clamped</a> to within this limited grid.

	To <dfn local-lt=clamp>clamp a grid area</dfn>:
	* If the <a>grid area</a> would <a>span</a> outside the limited grid,
		its span is clamped to the last line of the limited <a>grid</a>.
	* If the <a>grid area</a> would be placed completely outside the limited grid,
		its span must be truncated to 1
		and the area repositioned into the last <a>grid track</a> on that side of the grid.

	<div class='example'>
		For example, if a UA only supported grids with at most 1000 tracks in each dimension,
		the following placement properties:

		<pre class="lang-css">
		.grid-item {
			grid-row: 500 / 1500;
			grid-column: 2000 / 3000;
		}
		</pre>

		Would end up being equivalent to:

		<pre class="lang-css">
		.grid-item {
			grid-row: 500 / 1001;
			grid-column: 1000 / 1001;
		}
		</pre>
	</div>

<!--
 ██████   ████████  ████ ████████        ████ ████████ ████████ ██     ██  ██████
██    ██  ██     ██  ██  ██     ██        ██     ██    ██       ███   ███ ██    ██
██        ██     ██  ██  ██     ██        ██     ██    ██       ████ ████ ██
██   ████ ████████   ██  ██     ██        ██     ██    ██████   ██ ███ ██  ██████
██    ██  ██   ██    ██  ██     ██        ██     ██    ██       ██     ██       ██
██    ██  ██    ██   ██  ██     ██        ██     ██    ██       ██     ██ ██    ██
 ██████   ██     ██ ████ ████████        ████    ██    ████████ ██     ██  ██████
-->

<h2 id="grid-items">
Grid Items</h2>

	Loosely speaking, the <dfn export id="grid-item" lt="grid item">grid items</dfn> of a <a>grid container</a>
	are boxes representing its <a>in-flow</a> contents.

	Each <a>in-flow</a> child of a <a>grid container</a>
	becomes a <a>grid item</a>,
	and each child <a>text sequence</a>
	is wrapped in an <a>anonymous</a> <a>block container</a> <a>grid item</a>.
	However, if the <a>text sequence</a> contains only
	<a href="https://www.w3.org/TR/CSS2/text.html#white-space-prop">white space</a>
	(i.e. characters that can be affected by the 'white-space' property)
	it is instead not rendered (just as if its <a>text nodes</a> were ''display:none'').

	<div class="example">
		<p>Examples of grid items:
		<pre class="lang-markup">
		&lt;div style="display: grid">

		  &lt;!-- grid item: block child -->
		  &lt;div id="item1">block&lt;/div>

		  &lt;!-- grid item: floated element; floating is ignored -->
		  &lt;div id="item2" style="float: left;">float&lt;/div>

		  &lt;!-- grid item: anonymous block box around inline content -->
		  anonymous item 3

		  &lt;!-- grid item: inline child -->
		  &lt;span>
		    item 4
		    &lt;!-- grid items do not <a href="https://www.w3.org/TR/CSS2/visuren.html#anonymous-block-level">split</a> around blocks -->
		    &lt;q style="display: block" id=not-an-item>item 4&lt;/q>
		    item 4
		  &lt;/span>
		&lt;/div>
		</pre>

		<figure>
			<figcaption>grid items determined from above code block</figcaption>
			<a href="examples/grid-item-determination.html">
				<object type="image/png" data="images/grid-item-determination.png">
					<ol>
						<li>grid item containing <samp>block</samp>.
						<li>grid item containing <samp>float</samp>.
						<li>(Anonymous, unstyleable) grid item containing <samp>anonymous item 3</samp>.
						<li>grid item containing three blocks in succession:
							<ul>
								<li>Anonymous block containing <samp>item 4</samp>.
								<li><code>&lt;q></code> element block containing <samp>item 4</samp>.
								<li>Anonymous block containing <samp>item 4</samp>.
							</ul>
					</ol>
				</object>
			</a>
		</figure>

	</div>

	Note: inter-element white space disappears:
	it does not become its own grid item,
	even though inter-element text <em>does</em> 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.

<h3 id="grid-item-display">
	Grid Item Display</h3>

	Unless it is a [=subgrid=],
	a <a>grid item</a> [=establishes an independent formatting context=] for its contents.
	However, grid items are <dfn export>grid-level</dfn> boxes, not block-level boxes:
	they participate in their container's <a>grid formatting context</a>,
	not in a block formatting context.

	If the [=computed value|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 <a href="https://www.w3.org/TR/CSS2/visuren.html#dis-pos-flo">CSS2.1&sect;9.7</a> [[!CSS2]]
	and [[css-display-3#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 element|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 <a>grid item</a>,
	it is blockified first,
	and so anonymous box creation will not happen.
	For example, two contiguous <a>grid items</a> with ''display: table-cell''
	will become two separate ''display: block'' <a>grid items</a>,
	instead of being wrapped into a single anonymous table.

<h3 id="grid-item-sizing">
	Grid Item Sizing</h3>

	A <a>grid item</a> is sized within the containing block defined by its <a>grid area</a>.

	[=Grid item=] calculations for [=automatic sizes=] in a given dimensions
	vary by their [[css-align-3#self-alignment|self-alignment values]]:

	: ''align-self/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 [[CSS2#q10.0]].)

	: ''align-self/stretch''
	::
		Use the [=inline size=] calculation rules for non-replaced boxes
		(defined in [[CSS2/visudet#blockwidth]]),
		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 ''width/fit-content''.

	<div class="note">
		The following informative table summarizes the automatic sizing of grid items:

		<table class=data>
			<caption>Summary of automatic sizing behavior of grid items</caption>
			<thead>
				<tr>
					<th>Alignment
					<th>Non-replaced Element Size
					<th>Replaced Element Size
			<tbody>
				<tr>
					<th scope=row>''align-self/normal''
					<td>Fill grid area
					<td>Use [=natural size=]
				<tr>
					<th scope=row>''align-self/stretch''
					<td>Fill grid area
					<td>Fill grid area
				<tr>
					<th scope=row>''align-self/start''/''align-self/center''/etc.
					<td>''width/fit-content'' sizing (like floats)
					<td>Use [=natural size=]
		</table>
	</div>

	Note: The ''min-width/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 <a>flex item</a>.
	See [[#min-size-auto]].

<!--
<h3 id="position-grid">
Non-children Grid Items</h3>

	<p class="issue">
		This is a proposal to create the ability to have descendants of a grid item participate in a grid layout,
		similar to the behavior defined by the Template Layout module.

		A descendant of the grid can be pulled out of flow and participate directly in the grid
		by assigning it ''position: grid''.
		An element with ''position: grid'' is pulled out of flow and participates as a grid item
		belonging to the first ancestor with ''display: grid''.
		If the element is positioned using named lines or slots,
		it belongs to the first ancestor with ''display: grid'' that has all of the corresponding named lines/slots.
		If no such ancestor exists, the item remains in flow.

	<p class="issue">
		Alternatively, the item can just go into the first grid,
		and missing names are treated as <a value for="<grid-line>">auto</a>.
-->

<h3 id='order-property'>
Reordered Grid Items: the 'order' property</h3>

	The 'order' property also applies to <a>grid items</a>.
	It affects their [[#grid-auto-flow-property|auto-placement]] and [[#z-order|painting order]].

	Advisement: As with reordering flex items,
	the 'order' property must only be used
	when the visual order needs to be <em>out-of-sync</em>
	with the speech and navigation order;
	otherwise the underlying document source should be reordered instead.
	See [[css-display-3#order-accessibility]]
	in [[CSS-DISPLAY-3]].

<h3 id='item-margins'>
Grid Item Margins and Paddings</h3>

	As adjacent grid items are independently contained
	within the containing block formed by their <a>grid areas</a>,
	the margins of adjacent <a>grid items</a> do not
	<a href="https://www.w3.org/TR/CSS2/box.html#collapsing-margins">collapse</a>.

	Percentage margins and paddings on <a>grid items</a>,
	like those on <a>block boxes</a>,
	are resolved against the <a>inline size</a> of their <a>containing block</a>,
	e.g. left/right/top/bottom percentages
	all resolve against their <a>containing block</a>’s <em>width</em>
	in horizontal <a>writing modes</a>.

	Auto margins expand to absorb extra space in the corresponding dimension,
	and can therefore be used for alignment.
	See [[#auto-margins]]

<h3 id='z-order'>
Z-axis Ordering: the 'z-index' property</h3>

	<a>Grid items</a> can overlap when they are positioned into intersecting <a>grid areas</a>,
	or even when positioned in non-intersecting areas because of negative margins or positioning.
	The painting order of <a>grid items</a> is exactly the same as inline blocks [[CSS2]],
	except that <a>order-modified document order</a> is used in place of raw document order,
	and 'z-index' values other than <a value for=z-index>auto</a> 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.

	<p class='note'>
		Note: Descendants that are positioned outside a grid item still participate in any stacking context established by the grid item.

	<div class="example">
		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.

		<figure>
			<img src="images/drawing-order.png">

			<figcaption>Drawing order controlled by z-index and source order.</figcaption>
		</figure>

		<pre>
			&lt;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; }
			&lt;/style>

			&lt;div id="grid">
				&lt;div id="A">A&lt;/div>
				&lt;div id="B">B&lt;/div>
				&lt;div id="C">C&lt;/div>
				&lt;div id="D">D&lt;/div>
				&lt;div id="E">E&lt;/div>
			&lt;/div>
		</pre>
	</div>

<!--
██     ██ ████ ██    ██
███   ███  ██  ███   ██          ██   ██
████ ████  ██  ████  ██           ██ ██
██ ███ ██  ██  ██ ██ ██ ███████ █████████
██     ██  ██  ██  ████           ██ ██
██     ██  ██  ██   ███          ██   ██
██     ██ ████ ██    ██
-->

<h3 id="min-size-auto">
Automatic Minimum Size of Grid Items</h3>

	Note: Much of the sizing terminology used in this section
	(and throughout the rest of the specification)
	is defined in <a href="https://www.w3.org/TR/css-sizing-3/">CSS Intrinsic and Extrinsic Sizing</a> [[!CSS-SIZING-3]].

	To provide a more reasonable default <a>minimum size</a> for <a>grid items</a>,
	the used value of its <a>automatic minimum size</a> in a given axis
	is the <a>content-based minimum size</a> if all of the following are true:

	* its [=computed value|computed=] 'overflow' is not a [=scrollable overflow value=]
	* it spans at least one [=track=] in that axis
		whose <a>min track sizing function</a> is ''grid-template-rows/auto''
	* if it spans more than one track in that axis, none of those tracks are [=flexible track|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#intrinsic-contribution]] apply.

	The <dfn>content-based minimum size</dfn> for a <a>grid item</a> in a given dimension is
	its <a>specified size suggestion</a> if it exists,
	otherwise its <a>transferred size suggestion</a> if that exists
	and the element is [=replaced element|replaced=],
	else its <a>content size suggestion</a>,
	see below.
	However,
<!--
	to prevent the <a>content-based minimum size</a>
	from forcing overflow of its fixed-size grid area,
-->
	if in a given dimension
	the <a>grid item</a> spans only <a>grid tracks</a>
	that have a <a lt="fixed sizing function">fixed</a> <a>max track sizing function</a>,
	then its <a>specified size suggestion</a> and <a>content size suggestion</a> in that dimension
	(and its input from this dimension
	to the <a>transferred size suggestion</a> in the opposite dimension)
	are further clamped to less than or equal to the <a>stretch fit</a>
	into the <a>grid area</a>’s maximum size in that dimension,
	as represented by the sum of those <a>grid tracks</a>’ <a>max track sizing functions</a>
	plus any intervening <a lt="fixed sizing function">fixed</a> <a>gutters</a>.

	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 [[css-sizing-3#min-content-zero|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 <em>not</em> clamp
	the [=content-based minimum size=] in the same way as a
	<a lt="fixed sizing function">fixed</a> <a>max track sizing function</a>.

	The <a>content size suggestion</a>, <a>specified size suggestion</a>, and <a>transferred size suggestion</a>
	used in this calculation account for the relevant min/max/preferred size properties
	so that the <a>content-based minimum size</a> does not interfere with any author-provided constraints,
	and are defined below:

	<dl>
		<dt><dfn>specified size suggestion</dfn>
		<dd>
			If the item’s [=preferred size=] in the relevant axis is <a>definite</a>,
			then the <a>specified size suggestion</a> is that size.
			It is otherwise undefined.

		<dt><dfn>transferred size suggestion</dfn>
		<dd>
			If the item has a [=preferred aspect ratio=]
			and its [=preferred size=] in the opposite axis is <a>definite</a>,
			then the <a>transferred size suggestion</a> is that size
			(clamped by the opposite-axis [=minimum size|minimum=] and [=maximum sizes=] if they are <a>definite</a>),
			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=]).

		<dt><dfn>content size suggestion</dfn>
		<dd>
			The <a>content size suggestion</a> is
			the <a>min-content size</a> in the relevant axis,
			clamped, if it has a [=preferred aspect ratio=],
			by any <a>definite</a> opposite-axis [=minimum size|minimum=] and [=maximum sizes=]
			converted through the aspect ratio.
	</dl>

	For the purpose of calculating an intrinsic size of the box
	(e.g. the box’s <a>min-content size</a>),
	a <a>content-based minimum size</a> causes the box’s size in that axis to become indefinite
	(even if e.g. its 'width' property specifies a <a>definite</a> size).
	Note this means that percentages calculated against this size
	will [=behave as auto=].

	For any purpose <em>other than</em> 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 <em>before</em> this minimum was applied,
	it must be re-resolved against the new size after it is applied.

	<div class="note" id="min-size-opt">
		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.)
	</div>

<h2 id='grid-definition'>
Defining the Grid</h2>

<!--
████████ ██     ██ ████████  ██       ████  ██████  ████ ████████
██        ██   ██  ██     ██ ██        ██  ██    ██  ██     ██
██         ██ ██   ██     ██ ██        ██  ██        ██     ██
██████      ███    ████████  ██        ██  ██        ██     ██
██         ██ ██   ██        ██        ██  ██        ██     ██
██        ██   ██  ██        ██        ██  ██    ██  ██     ██
████████ ██     ██ ██        ████████ ████  ██████  ████    ██
-->

<h3 id='explicit-grids'>
The Explicit Grid</h3>

	The three properties 'grid-template-rows', 'grid-template-columns', and 'grid-template-areas'
	together define the <dfn export local-lt="explicit">explicit grid</dfn> of a <a>grid container</a>
	by specifying its <dfn lt="explicit grid track | explicit grid row | explicit grid column">explicit grid tracks</dfn>.
	The final grid may end up larger due to <a>grid items</a> placed outside the <a>explicit grid</a>;
	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 <a>explicit grid</a> 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 <em>any</em> <a>explicit</a> tracks
	the <a>explicit grid</a> still contains one <a>grid line</a> in each axis.

	Numeric indexes in the <a>grid-placement properties</a>
	count from the edges of the <a>explicit grid</a>.
	Positive indexes count from the <a>start</a> side
	(starting from 1 for the <a>start</a>-most <a>explicit</a> line),
	while negative indexes count from the <a>end</a> side
	(starting from -1 for the <a>end</a>-most <a>explicit</a> line).

	The 'grid' and 'grid-template' properties are <a>shorthands</a>
	that can be used to set all three <dfn>explicit grid properties</dfn>
	('grid-template-rows', 'grid-template-columns', and 'grid-template-areas')
	at the same time.
	The 'grid' shorthand also resets properties controlling the <a>implicit grid</a>,
	whereas the 'grid-template' property leaves them unchanged.

<h3 id='track-sizing'>
Explicit Track Sizing: the 'grid-template-rows' and 'grid-template-columns' properties</h3>

	<pre class='propdef'>
	Name: grid-template-columns, grid-template-rows
	Value: none | <<track-list>> | <<auto-track-list>> | subgrid <<line-name-list>>?
	Initial: none
	Applies to: <a>grid containers</a>
	Inherited: no
	Percentages: refer to corresponding dimension of the content area
	Computed value: the keyword ''grid-template-columns/none'' or a [=computed track list=]
	Animation type: if the list lengths match, by computed value type per item in the [=computed track list=] (see [[#computed-tracks]] and [[#repeat-interpolation]]); discrete otherwise
	</pre>

	These properties specify,
	as a space-separated <dfn export>track list</dfn>,
	the [=line names=] and <a>track sizing functions</a> of the <a>grid</a>.
	The 'grid-template-columns' property specifies the <a>track list</a> for the grid's columns,
	while 'grid-template-rows' specifies the <a>track list</a> for the grid's rows.

	Values have the following meanings:

	<dl dfn-type="value" dfn-for="grid-template-rows, grid-template-columns">
		<dt><dfn>none</dfn>
		<dd>
			Indicates that no <a>explicit</a> grid tracks are created by this property
			(though <a>explicit grid</a> tracks could still be created by 'grid-template-areas').

			Note: In the absence of an <a>explicit grid</a> any rows/columns will be [[#implicit-grids|implicitly generated]],
			and their size will be determined by the 'grid-auto-rows' and 'grid-auto-columns' properties.

		<dt><dfn id="track-listing"><<track-list>> | <<auto-track-list>></dfn>
		<dd>
			Specifies the <a>track list</a> as a series of <a>track sizing functions</a>
			and [=line names=].
			Each <dfn dfn lt="track sizing function|sizing function">track sizing function</dfn> can be specified as a length,
			a percentage of the <a>grid container</a>’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 <a lt="min track sizing function">min</a>
			and <a>max track sizing functions</a> for the column or row.

		<dt><dfn id="subgrid-listing">subgrid <<line-name-list>>?</dfn>
		<dd>
			The <dfn value for="grid-template-rows, grid-template-columns">subgrid</dfn> value
			indicates that the grid will adopt the spanned portion
			of its [=parent grid=] in that axis
			(the <dfn dfn for local-lt="subgridded">subgridded axis</dfn>).
			Rather than being specified explicitly,
			the sizes of the grid rows/columns
			will be taken from the [=parent grid=]'s definition,
			and the <a>subgrid</a>’s items will participate
			in the <a href="https://www.w3.org/TR/css-grid-1/#algo-content">intrinsic size calculations</a> ([[css-grid-1#algo-content]])
			of any tracks shared with the [=parent grid=].
			Essentially,
			<a>subgrids</a> 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, ''grid-template-rows/none'',
			and the [=grid container=] is not a [=subgrid=].

			An axis that is not [=subgridded=] is a <dfn dfn for>standalone axis</dfn>.
	</dl>

	The syntax of a <a>track list</a> is:

	<pre class=prod>
		<dfn>&lt;track-list></dfn>          = [ <<line-names>>? [ <<track-size>> | <<track-repeat>> ] ]+ <<line-names>>?
		<dfn>&lt;auto-track-list></dfn>     = [ <<line-names>>? [ <<fixed-size>> | <<fixed-repeat>> ] ]* <<line-names>>? <<auto-repeat>>
		                        [ <<line-names>>? [ <<fixed-size>> | <<fixed-repeat>> ] ]* <<line-names>>?
		<dfn>&lt;explicit-track-list></dfn> = [ <<line-names>>? <<track-size>> ]+ <<line-names>>?

		<dfn>&lt;line-name-list></dfn>      = [ <<line-names>> | <<name-repeat>> ]+
		<dfn>&lt;track-size></dfn>          = <<track-breadth>> | minmax( <<inflexible-breadth>> , <<track-breadth>> ) | fit-content( <<length-percentage [0,∞]>> )
		<dfn>&lt;fixed-size></dfn>          = <<fixed-breadth>> | minmax( <<fixed-breadth>> , <<track-breadth>> ) | minmax( <<inflexible-breadth>> , <<fixed-breadth>> )
		<dfn>&lt;track-breadth></dfn>       = <<length-percentage [0,∞]>> | <<flex [0,∞]>> | min-content | max-content | auto
		<dfn>&lt;inflexible-breadth></dfn>  = <<length-percentage [0,∞]>> | min-content | max-content | auto
		<dfn>&lt;fixed-breadth></dfn>       = <<length-percentage [0,∞]>>
		<dfn>&lt;line-names></dfn>          = '[' <<custom-ident>>* ']'
	</pre>

	Where the component values are defined as follows&hellip;

<h4 id="track-sizes">
Track Sizes</h4>

	<dl dfn-for="grid-template-columns, grid-template-rows" dfn-type=value>
		<dt><dfn><<length-percentage [0,∞]>></dfn>
		<dd>
			A non-negative length or percentage, as defined by CSS3 Values. [[!CSS-VALUES-3]]

			<<percentage>> values are relative to
			the <a lt="inner size">inner</a> <a>inline size</a>
			of the <a>grid container</a> in column <a>grid tracks</a>,
			and the <a lt="inner size">inner</a> <a>block size</a>
			of the <a>grid container</a> in row <a>grid tracks</a>.
			If the size of the <a>grid container</a>
			depends on the size of its tracks,
			then the <<percentage>>
			must be treated as <a value for=width>auto</a>,
			for the purpose of calculating the intrinsic sizes of the <a>grid container</a>
			and then resolve against that resulting <a>grid container</a> size
			for the purpose of laying out the <a>grid</a> and its items.

		<dt><dfn><<flex [0,∞]>></dfn>
		<dd>
			A non-negative dimension with the unit ''fr'' specifying the track's <dfn dfn noexport>flex factor</dfn>.
			Each <<flex>>-sized track takes a share of the remaining space in proportion to its <a>flex factor</a>.
			For example, given a track listing of ''1fr 2fr'',
			the tracks will take up ⅓ and ⅔ of the <a>leftover space</a>, respectively.
			See [[#fr-unit]] for more details.

			Note: If the sum of the <a>flex factors</a> is less than 1,
			they'll take up only a corresponding fraction of the <a>leftover space</a>,
			rather than expanding to fill the entire thing.

			When appearing outside a ''minmax()'' notation,
			implies an automatic minimum (i.e. ''minmax(auto, <<flex>>)'').

		<dt><dfn function lt="minmax()">minmax(<var>min</var>, <var>max</var>)</dfn>
		<dd>
			Defines a size range
			greater than or equal to <var>min</var>
			and less than or equal to <var>max</var>.
			If the <var>max</var> is less than the <var>min</var>,
			then the <var>max</var> will be floored by the <var>min</var>
			(essentially yielding ''minmax(<var>min</var>, <var>min</var>)'').
			As a maximum, a <<flex>> value sets the track's <a>flex factor</a>;
			it is invalid as a minimum.

			Note: A future level of this spec may allow <<flex>> minimums,
			and will update the <a>track sizing algorithm</a> to account for this correctly

		<dt><dfn>auto</dfn>
		<dd>
			As a <em>maximum</em>: represents the largest <a>max-content contribution</a>
			of the <a>grid items</a> occupying the <a>grid track</a>;
			however, unlike ''max-content'',
			allows expansion of the track
			by the 'align-content' and 'justify-content' properties.

			As a <em>minimum</em>: represents the largest <a>minimum size</a>
			(specified by 'min-width'/'min-height')
			of the <a>grid items</a> occupying the <a>grid track</a>.
			(This initially is often, but not always,
			equal to a ''min-content'' minimum--
			see [[#min-size-auto]].)

			When appearing outside a ''minmax()'' notation:
			equivalent to ''minmax(auto, auto)'',
			representing the range between
			the minimum and maximum described above.
			(This behaves similar to ''minmax(min-content, max-content)'' in the most basic cases,
			but with extra abilities.)

		<dt><dfn>max-content</dfn>
		<dd>
			Represents the largest <a>max-content contribution</a>
			of the <a>grid items</a> occupying the <a>grid track</a>.

		<dt><dfn>min-content</dfn>
		<dd>
			Represents the largest <a>min-content contribution</a>
			of the  <a>grid items</a> occupying the <a>grid track</a>.

		<dt><dfn function lt="fit-content()">fit-content( <<length-percentage>> )</dfn>
		<dd>
			Represents the formula
			<code>max(<var>minimum</var>, min(<var>limit</var>, ''max-content''))</code>,
			where <var>minimum</var> represents an ''grid-template-columns/auto'' minimum
			(which is often, but not always, equal to a ''min-content'' minimum),
			and <var>limit</var> is the <a>track sizing function</a>
			passed as an argument to ''fit-content()''.
			This is essentially calculated as the smaller of
			''minmax(auto, max-content)'' and ''minmax(auto, <var>limit</var>)''.
	</dl>

	<div class='example'>
		Given the following 'grid-template-columns' declaration:

		<pre>grid-template-columns: 100px 1fr max-content minmax(min-content, 1fr);</pre>

		Five grid lines are created:

		<ol>
			<li>
				At the start edge of the <a>grid container</a>.

			<li>
				100px from the start edge of the <a>grid container</a>.

			<li>
				A distance from the previous line equal to half the <a>free space</a>
				(the width of the <a>grid container</a>, minus the width of the non-flexible <a>grid tracks</a>).

			<li>
				A distance from the previous line equal to the maximum size of any <a>grid items</a>
				belonging to the column between these two lines.

			<li>
				A distance from the previous line at least as large as the largest minimum size of any <a>grid items</a>
				belonging to the column between these two lines,
				but no larger than the other half of the <a>free space</a>.
		</ol>

		If the non-flexible sizes
		(''100px'', ''max-content'', and ''min-content'')
		sum to larger than the <a>grid container</a>’s width,
		the final <a>grid line</a> will be a distance equal to their sum away from the start edge of the <a>grid container</a>
		(the ''1fr'' sizes both resolve to ''0'').
		If the sum is less than the <a>grid container</a>’s width,
		the final <a>grid line</a> will be exactly at the end edge of the <a>grid container</a>.
		This is true in general whenever there's at least one <<flex>> value among the <a>grid track</a> sizes.
	</div>

	<div class='example'>
		Additional examples of valid <a>grid track</a> definitions:

		<pre>
			/* 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);
		</pre>
	</div>

	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.

<!--
██    ██    ███    ██     ██ ████████ ████████        ██       ████ ██    ██ ████████  ██████
███   ██   ██ ██   ███   ███ ██       ██     ██       ██        ██  ███   ██ ██       ██    ██
████  ██  ██   ██  ████ ████ ██       ██     ██       ██        ██  ████  ██ ██       ██
██ ██ ██ ██     ██ ██ ███ ██ ██████   ██     ██       ██        ██  ██ ██ ██ ██████    ██████
██  ████ █████████ ██     ██ ██       ██     ██       ██        ██  ██  ████ ██             ██
██   ███ ██     ██ ██     ██ ██       ██     ██       ██        ██  ██   ███ ██       ██    ██
██    ██ ██     ██ ██     ██ ████████ ████████        ████████ ████ ██    ██ ████████  ██████
-->

<h4 id='named-lines'>
Naming Grid Lines: the <css>[<<custom-ident>>*]</css> syntax</h4>

	While <a>grid lines</a> can always be referred to by their numerical index,
	<dfn export lt="line name">line names</dfn>
	can make the <a>grid-placement properties</a> easier to understand and maintain.
	[=Line names=] can be <dfn lt="explicitly-assigned line name">explicitly assigned</dfn> with the 'grid-template-rows' and 'grid-template-columns' properties,
	or [=implicitly-assigned line name|implicitly assigned=] by <a>named grid areas</a> with the 'grid-template-areas' property.

	<div class='example'>
		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.

		<pre>
			#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];
			}
		</pre>

		<figure class="figure">
			<img class="figure" alt="Image: Named Grid Lines." src="images/grid-named-lines.png">
			<figcaption>Named Grid Lines.</figcaption>
		</figure>
	</div>

	A [=line name=] cannot be <css>span</css> or <css>auto</css>,
	i.e. the <<custom-ident>> in the <<line-names>> production
	excludes the keywords <css>span</css> and <css>auto</css>.

<!--
████████  ████████ ████████  ████████    ███    ████████   ███ ███
██     ██ ██       ██     ██ ██         ██ ██      ██     ██     ██
██     ██ ██       ██     ██ ██        ██   ██     ██    ██       ██
████████  ██████   ████████  ██████   ██     ██    ██    ██       ██
██   ██   ██       ██        ██       █████████    ██    ██       ██
██    ██  ██       ██        ██       ██     ██    ██     ██     ██
██     ██ ████████ ██        ████████ ██     ██    ██      ███ ███
-->

<h4 id='repeat-notation'>
Repeating Rows and Columns: the ''repeat()'' notation</h4>

	The <dfn for="<track-repeat>,<auto-repeat>,<fixed-repeat>">repeat()</dfn> notation
	represents a repeated fragment of the <a>track list</a>,
	allowing a large number of columns or rows that exhibit a recurring pattern
	to be written in a more compact form.

	<div class='example'>
		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.

		<pre>
			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;
		</pre>
	</div>

<h5 id='repeat-syntax'>
Syntax of ''repeat()''</h5>

	The generic form of the ''repeat()'' syntax is, approximately,

	<pre class='prod'>
		repeat( [ <<integer [1,∞]>> | auto-fill | auto-fit ] , <<track-list>> )
	</pre>

	The first argument specifies the number of repetitions.
	The second argument is a <a>track list</a>,
	which is repeated that number of times.
	However, there are some restrictions:

		* The ''repeat()'' notation can’t be nested.
		* Automatic repetitions (''auto-fill'' or ''auto-fit'')
			cannot be combined with
			fully <a lt="intrinsic sizing function">intrinsic</a>
			or <a lt="flexible sizing function">flexible</a> sizes
			(see grammar).

	Thus the precise syntax of the ''repeat()'' notation
	has several forms:

	<pre class='prod'>
		<dfn><<track-repeat>></dfn> = repeat( [ <<integer [1,∞]>> ] , [ <<line-names>>? <<track-size>> ]+ <<line-names>>? )
		<dfn><<auto-repeat>></dfn>  = repeat( [ auto-fill | auto-fit ] , [ <<line-names>>? <<fixed-size>> ]+ <<line-names>>? )
		<dfn><<fixed-repeat>></dfn> = repeat( [ <<integer [1,∞]>> ] , [ <<line-names>>? <<fixed-size>> ]+ <<line-names>>? )
		<dfn><<name-repeat>></dfn> = repeat( [ <<integer [1,∞]>> | auto-fill ], <<line-names>>+)
	</pre>

	* The <<track-repeat>> variant can represent the repetition of any <<track-size>>,
		but is limited to a fixed number of repetitions.
	* The <<auto-repeat>> variant can repeat automatically to fill a space,
		but requires <a>definite</a> track sizes so that the number of repetitions can be calculated.
		It can only appear once in the <a>track list</a>,
		but the same <a>track list</a> can also contain <<fixed-repeat>>s.
	* The <<name-repeat>> variant is for adding [=line names=] to [=subgrids=].
		It can only be used with the ''grid-template-rows/subgrid'' keyword
		and cannot specify track sizes, only [=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]''.

<h5 id="auto-repeat">
Repeat-to-fill: ''auto-fill'' and ''auto-fit'' repetitions</h5>

	On 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 <a>grid span</a>
	(falling back to 0 if the span is already fulfilled).

	Otherwise on a [=standalone axis=],
	when <dfn value for="repeat()">auto-fill</dfn> is given as the repetition number,
	if the <a>grid container</a> has a <a>definite</a> [=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 <a>grid</a> to overflow
	the <a>content box</a> of its <a>grid container</a>
	taking 'gap' into account;
	if any number of repetitions would overflow,
	then 1 repetition.
	Otherwise, if the <a>grid container</a> has a <a>definite</a> [=minimum size=] in the relevant axis,
	the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement.
	Otherwise, the specified <a>track list</a> repeats only once.

	For this purpose,
	each track is treated as its <a>max track sizing function</a> if that is <a>definite</a>
	or else its [=min track sizing function=] if that is definite.
	If both are definite, floor the <a>max track sizing function</a>
	by the <a>min track sizing function</a>.
	If neither are definite,
	the number of repetitions is one.

	<div class="example">
		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.

		<pre>
			body {
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(25ch, 1fr));
			}
		</pre>
	</div>

	The <dfn value for="repeat()">auto-fit</dfn> keyword behaves the same as ''auto-fill'',
	except that after [[#auto-placement-algo|grid item placement]]
	any empty repeated tracks are <a>collapsed</a>.
	An empty track is one with no <a>in-flow</a> grid items placed into or spanning across it.
	(This can result in <em>all</em> tracks being <a>collapsed</a>,
	if they're all empty.)

	A <dfn export local-lt="collapse | collapsed track">collapsed grid track</dfn>
	is treated as having a fixed <a>track sizing function</a> of ''0px'',
	and the <a>gutters</a> on either side of it--
	including any space allotted through <a>distributed alignment</a>--
	<a lt="collapsed gutter">collapse</a>.

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

<h5 id="repeat-interpolation">
Interpolation/Combination of ''repeat()''</h5>

	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 <a>computed track lists</a>
	<a>by computed value</a>
	(just like combining a top-level track list).
	They otherwise combine <a lt=discrete>discretely</a>.

<!--
████████ ████████        ██     ██ ██    ██ ████ ████████
██       ██     ██       ██     ██ ███   ██  ██     ██
██       ██     ██       ██     ██ ████  ██  ██     ██
██████   ████████        ██     ██ ██ ██ ██  ██     ██
██       ██   ██         ██     ██ ██  ████  ██     ██
██       ██    ██        ██     ██ ██   ███  ██     ██
██       ██     ██        ███████  ██    ██ ████    ██
-->

<h4 id='fr-unit'>
Flexible Lengths: the ''fr'' unit</h4>

	A <dfn export>flexible length</dfn> or <dfn><<flex>></dfn> is a dimension
	with the <dfn value for="<flex>" lt="fr|fr unit">fr</dfn> unit,
	which represents a fraction of the <a>leftover space</a> in the <a>grid container</a>.
	Tracks sized with ''fr'' units are called <dfn>flexible tracks</dfn>
	as they flex in response to <a>leftover space</a>
	similar to how <a>flex items</a> with a zero base size fill space in a <a>flex container</a>.

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

	Each column or row's share of the <a>leftover space</a> can be computed as the column or row's
	<code>&lt;flex> * &lt;leftover space> / &lt;sum of all <a>flex factors</a>&gt;</code>.

	<details class=note>
		<summary><<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.</summary>

		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 <em>less</em> 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 [[#algo-flex-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 <em>none</em> 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 <em>specifically</em> what's desired,
		authors should stick to values &ge; 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.
	</details>

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

<!--
 ██████   ███████  ██     ██ ████████  ██     ██ ████████ ████████ ████████
██    ██ ██     ██ ███   ███ ██     ██ ██     ██    ██    ██       ██     ██
██       ██     ██ ████ ████ ██     ██ ██     ██    ██    ██       ██     ██
██       ██     ██ ██ ███ ██ ████████  ██     ██    ██    ██████   ██     ██
██       ██     ██ ██     ██ ██        ██     ██    ██    ██       ██     ██
██    ██ ██     ██ ██     ██ ██        ██     ██    ██    ██       ██     ██
 ██████   ███████  ██     ██ ██         ███████     ██    ████████ ████████
-->

<h4 id='computed-tracks'>
Computed Value of a Track Listing</h4>

	The <dfn>computed track list</dfn> of a non-''subgrid'' axis
	is a <a spec=infra>list</a>
	alternating between [=line name sets=] and [=track sections=],
	with the first and last items being [=line name sets=].

	A <dfn>line name set</dfn> is a (potentially empty) <a spec=infra for="/">set</a>
	of identifiers representing line names.

	A <dfn>track section</dfn> is either:

	* a ''minmax()'' functional notation representing a single track's size,
		with each <<length-percentage>> computed
		(a <dfn noexport>computed track size</dfn>)
	* a ''repeat()'' functional notation representing a repeated track list section,
		with its <<integer>> computed
		and its <<track-list>> represented as a [=computed track list=]
		(a <dfn>computed repeat notation</dfn>)

	The [=computed track list=] of a ''subgrid'' axis
	is the ''subgrid'' keyword followed by
	a <a spec=infra>list</a> of [=line name sets=]
	and [=computed repeat notations=]
	representing the line names specified for that axis.

<!--
████████  ████████  ██████   ███████  ██       ██     ██ ████████ ████████
██     ██ ██       ██    ██ ██     ██ ██       ██     ██ ██       ██     ██
██     ██ ██       ██       ██     ██ ██       ██     ██ ██       ██     ██
████████  ██████    ██████  ██     ██ ██       ██     ██ ██████   ██     ██
██   ██   ██             ██ ██     ██ ██        ██   ██  ██       ██     ██
██    ██  ██       ██    ██ ██     ██ ██         ██ ██   ██       ██     ██
██     ██ ████████  ██████   ███████  ████████    ███    ████████ ████████
-->

<h4 id='resolved-track-list'>
Resolved Value of a Track Listing</h4>

	The 'grid-template-rows' and 'grid-template-columns' properties are
	<a>resolved value special case properties</a>. [[!CSSOM]]

<h5 id="resolved-track-list-standalone">
Resolved Value of a Standalone Track Listing</h5>

	When an element generates a [=grid container=] box,
	the <a href="https://www.w3.org/TR/cssom/#resolved-values">resolved value</a>
	of its 'grid-template-rows' or 'grid-template-columns' property
	in a [=standalone axis=]
	is the <a>used value</a>,
	serialized with:

	<ul>
		<li>
			Every track listed individually,
			whether implicitly or explicitly created,
			without using the ''repeat()'' notation.

		<li>
			Every track size given as a length in pixels,
			regardless of sizing function.

		<li>
			Adjacent line names collapsed into a single bracketed set.
	</ul>

	<div class=issue>
		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 <em>cannot</em>
		actually specify implicit track sizes in those properties!
		So 'grid-template-rows' and 'grid-template-columns' values
		might not round-trip correctly:

		<pre highlight=js>
		const s = getComputedStyle(gridEl);
		gridEl.style.gridTemplateRows = s.gridTemplateRows;
		// Code like this <em>should</em> be a no-op,
		// but if there are any implicit rows,
		// this will convert them into explicit rows,
		// possibly changing how grid items are positioned
		// and altering the overall size of the grid!
		</pre>

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

	Otherwise, (e.g. when the element has ''display: none'' or is not a <a>grid container</a>)
	the resolved value is simply the <a>computed value</a>.

	<div class="example">
		<pre class="lang-html">
			&lt;style>
			#grid {
				width: 500px;
				grid-template-columns:
				  [a]     auto
				  [b]     minmax(min-content, 1fr)
				  [b c d] repeat(2, [e] 40px)
				          repeat(5, auto);
			}
			&lt;/style>
			&lt;div id="grid">
			  &lt;div style="grid-column-start: 1; width: 50px">&lt;/div>
			  &lt;div style="grid-column-start: 9; width: 50px">&lt;/div>
			&lt;/div>
			&lt;script>
			  var gridElement = document.getElementById("grid");
			  getComputedStyle(gridElement).gridTemplateColumns;
			  // [a] 50px [b] 320px [b c d e] 40px [e] 40px 0px 0px 0px 0px 50px
			&lt;/script>
		</pre>
	</div>

	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.

	ISSUE: The CSS Working Group is considering whether to also return used values
	for the <a>grid-placement properties</a>
	and is looking for feedback, especially from implementors.
	See <a href="https://github.com/w3c/csswg-drafts/issues/2681">discussion</a>.

<h5 id="resolved-track-list-subgrid">
Resolved Value of a Subgridded Track Listing</h5>


	When 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 value|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.

	<div class="example">
		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=]:

		<pre class="lang-css">
			specified: subgrid [a] repeat(auto-fill, [b]) [c]
			resolved:  subgrid [a] [b] [b] [b] [c]
		</pre>

		<pre class=lang-css>
			specified: subgrid [a] [a] [a] [a] repeat(auto-fill, [b]) [c] [c]
			resolved:  subgrid [a] [a] [a] [a] [c]
		</pre>

		<pre class="lang-css">
			specified: subgrid [] [a]
			resolved:  subgrid [] [a] [] [] []
		</pre>

		<pre class="lang-css">
			specified: subgrid [a] [b] [c] [d] [e] [f]
			resolved:  subgrid [a] [b] [c] [d] [e]
		</pre>
	</div>

	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.

<!--
 ██████   ████████  ████ ████████           ███    ████████  ████████    ███     ██████
██    ██  ██     ██  ██  ██     ██         ██ ██   ██     ██ ██         ██ ██   ██    ██
██        ██     ██  ██  ██     ██        ██   ██  ██     ██ ██        ██   ██  ██
██   ████ ████████   ██  ██     ██       ██     ██ ████████  ██████   ██     ██  ██████
██    ██  ██   ██    ██  ██     ██       █████████ ██   ██   ██       █████████       ██
██    ██  ██    ██   ██  ██     ██       ██     ██ ██    ██  ██       ██     ██ ██    ██
 ██████   ██     ██ ████ ████████        ██     ██ ██     ██ ████████ ██     ██  ██████
-->

<h3 id="grid-template-areas-property">
Named Areas: the 'grid-template-areas' property</h3>

	<pre class='propdef'>
	Name: grid-template-areas
	Value: none | <<string>>+
	Initial: none
	Applies to: <a>grid containers</a>
	Inherited: no
	Percentages: n/a
	Computed value: the keyword ''grid-template-areas/none'' or a list of string values
	Animation type: discrete
	</pre>

	This property specifies <dfn export lt="named grid area">named grid areas</dfn>,
	which are not associated with any particular <a>grid item</a>,
	but can be referenced from the <a>grid-placement properties</a>.
	The syntax of the 'grid-template-areas' property also provides a visualization
	of the structure of the <a>grid</a>,
	making the overall layout of the <a>grid container</a> easier to understand.

	Values have the following meanings:

	<dl dfn-for="grid-template-areas" dfn-type=value>
		<dt><dfn>none</dfn>
		<dd>
			Indicates that no <a>named grid areas</a>,
			and likewise no <a>explicit grid</a> tracks,
			are defined by this property
			(though <a>explicit grid</a> tracks could still be created by 'grid-template-columns' or 'grid-template-rows').

			Note: In the absence of an <a>explicit grid</a> any rows/columns will be [[#implicit-grids|implicitly generated]],
			and their size will be determined by the 'grid-auto-rows' and 'grid-auto-columns' properties.

		<dt><dfn><<string>>+</dfn>
		<dd>
			A row is created for every separate string listed for the 'grid-template-areas' property,
			and a column is created for each cell in the string,
			when parsed as follows:

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

			<ul dfn-type="dfn">
				<li>
					A sequence of [=ident code points=],
					representing a <dfn>named cell token</dfn>
					with a name consisting of its code points.
				<li>
					A sequence of one or more "." (U+002E FULL STOP),
					representing a <dfn>null cell token</dfn>.

				<li>
					A sequence of <a>whitespace</a>,
					representing nothing
					(do not produce a token).

				<li>
					A sequence of any other characters,
					representing a <dfn>trash token</dfn>.
			</ul>

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

			<ul>
				<li>
					A <a>null cell token</a> represents an unnamed area in the <a>grid container</a>.

				<li>
					A <a>named cell token</a> creates a <a>named grid area</a> with the same name.
					Multiple <a>named cell tokens</a> within and between rows
					create a single <a>named grid area</a> that spans the corresponding <a>grid cells</a>.

				<li>
					A <a>trash token</a> is a syntax error,
					and makes the declaration invalid.
			</ul>

			All strings must define the same number of cell tokens
			([=named cell tokens=] and/or [=null cell tokens=]),
			and at least one cell token,
			or else the declaration is invalid.
			If a <a>named grid area</a> spans multiple <a>grid cells</a>,
			but those cells do not form a single filled-in rectangle,
			the declaration is invalid.

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


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

		<pre>
			#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; }
		</pre>
	</div>

<h4 id="serialize-template">
Serialization Of Template Strings</h4>

	When serializing either the [=specified value|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.

<h4 id="implicit-named-lines">
Implicitly-Assigned Line Names</h4>

	The 'grid-template-areas' property generates <dfn export lt="implicitly-assigned line name">implicitly-assigned line names</dfn> from the <a>named grid areas</a> in the template.
	For each <a>named grid area</a> <var>foo</var>, four <a>implicitly-assigned line names</a> are created:
	two named <css><var>foo</var>-start</css>, naming the row-start and column-start lines of the <a>named grid area</a>,
	and two named <css><var>foo</var>-end</css>, naming the row-end and column-end lines of the <a>named grid area</a>.

	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.

<h4 id="implicit-named-areas">
Implicitly-Named Areas</h4>

	Since a <a>named grid area</a> is referenced by the <a>implicitly-assigned line names</a> it produces,
	explicitly adding named lines of the same form (''foo-start''/''foo-end'')
	effectively creates a <a>named grid area</a>.
	Such <dfn export lt="implicitly-named area">implicitly-named areas</dfn> do not appear in the value of 'grid-template-areas',
	but can still be referenced by the <a>grid-placement properties</a>.

<!--
 ██████   ████████  ████ ████████          ████████ ████████ ██     ██ ████████  ██          ███    ████████ ████████
██    ██  ██     ██  ██  ██     ██            ██    ██       ███   ███ ██     ██ ██         ██ ██      ██    ██
██        ██     ██  ██  ██     ██            ██    ██       ████ ████ ██     ██ ██        ██   ██     ██    ██
██   ████ ████████   ██  ██     ██ ███████    ██    ██████   ██ ███ ██ ████████  ██       ██     ██    ██    ██████
██    ██  ██   ██    ██  ██     ██            ██    ██       ██     ██ ██        ██       █████████    ██    ██
██    ██  ██    ██   ██  ██     ██            ██    ██       ██     ██ ██        ██       ██     ██    ██    ██
 ██████   ██     ██ ████ ████████             ██    ████████ ██     ██ ██        ████████ ██     ██    ██    ████████
-->

<h3 id='explicit-grid-shorthand'>
Explicit Grid Shorthand: the 'grid-template' property</h3>

	<pre class='propdef shorthand'>
	Name: grid-template
	Value: none |
	Value: <nobr>[ <<'grid-template-rows'>> / <<'grid-template-columns'>> ]</nobr> |
	Value: <nobr>[ <<line-names>>? <<string>> <<track-size>>? <<line-names>>? ]+ [ / <<explicit-track-list>> ]?</nobr>
	Initial: none
	Applies to: <a>grid containers</a>
	</pre>

	The 'grid-template' property is a <a>shorthand</a> for setting
	'grid-template-columns', 'grid-template-rows', and 'grid-template-areas' in a single declaration.
	It has several distinct syntax forms:

	<dl dfn-for=grid-template dfn-type=value>
		<dt><dfn>none</dfn>
		<dd>
			Sets all three properties to their initial values (''grid-template-rows/none'').

		<dt><dfn id='grid-template-rowcol'><<'grid-template-rows'>> / <<'grid-template-columns'>></dfn>
		<dd>
			Sets 'grid-template-rows' and 'grid-template-columns' to the specified values, respectively,
			and sets 'grid-template-areas' to ''grid-template-areas/none''.

			<div class='example'>
				<pre>grid-template: auto 1fr / auto 1fr auto;</pre>

				is equivalent to

				<pre>
					grid-template-rows: auto 1fr;
					grid-template-columns: auto 1fr auto;
					grid-template-areas: none;
				</pre>
			</div>

		<dt><dfn id='grid-template-ascii'>[ <<line-names>>? <<string>> <<track-size>>? <<line-names>>? ]+ [ / <<explicit-track-list>> ]?</dfn>
		<dd>
			* Sets 'grid-template-areas' to the strings listed.
			* Sets 'grid-template-rows' to the <<track-size>>s following each string
				(filling in ''grid-template-rows/auto'' for any missing sizes),
				and splicing in the named lines defined before/after each size.
			* Sets 'grid-template-columns' to the track listing specified after the slash
				(or ''grid-template-columns/none'', if not specified).

			This syntax allows the author to align track names and sizes inline with their respective grid areas.

			<div class='example'>
				<pre>
					grid-template: [header-top] "a   a   a"     [header-bottom]
					                 [main-top] "b   b   b" 1fr [main-bottom]
					                          / auto 1fr auto;
				</pre>

				is equivalent to

				<pre>
					grid-template-areas: "a a a"
					                     "b b b";
					grid-template-rows: [header-top] auto [header-bottom main-top] 1fr [main-bottom];
					grid-template-columns: auto 1fr auto;
				</pre>

				and creates the following grid:

				<figure>
					<object data="images/grid-shorthand.svg" type="image/svg+xml">
						<ul>
							<li>Three columns, sized ''auto'', ''1fr'', and ''auto'', respectively
							<li>Two rows sized as ''auto'' and ''1fr'', respectively.
							<li>A line named both “header-top” and “a-start” at the top,
							a line with four names--
							“header-bottom”, “main-top”, “a-end”, and “b-start”--
							in the middle,
							a line named “main-bottom” and “b-end” at the bottom.
							<li>A line named “a-start” and “b-start” on the left edge,
							and a line named “a-end” and “b-end” on the right edge.
						</ul>
					</object>
					<figcaption>The grid created by the declarations above.
					(The “a/b-start/end” names are [=implicitly-assigned line name|implicitly assigned=] by the <a>named grid areas</a>.)
					</figcaption>
				</figure>
			</div>

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

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


<!--
████ ██     ██ ████████  ██       ████  ██████  ████ ████████
 ██  ███   ███ ██     ██ ██        ██  ██    ██  ██     ██
 ██  ████ ████ ██     ██ ██        ██  ██        ██     ██
 ██  ██ ███ ██ ████████  ██        ██  ██        ██     ██
 ██  ██     ██ ██        ██        ██  ██        ██     ██
 ██  ██     ██ ██        ██        ██  ██    ██  ██     ██
████ ██     ██ ██        ████████ ████  ██████  ████    ██
-->

<h3 id='implicit-grids'>
The Implicit Grid</h3>

	The 'grid-template-rows', 'grid-template-columns', and 'grid-template-areas' properties define a fixed number
	of tracks that form the <a>explicit grid</a>.
	When <a>grid items</a> are positioned outside of these bounds,
	the <a>grid container</a> generates
	<dfn export lt="implicit grid track|implicit grid row|implicit grid column">implicit grid tracks</dfn>
	by adding <dfn>implicit grid lines</dfn> to the <a>grid</a>.
	These lines together with the <a>explicit grid</a> form the <dfn export local-lt="implicit">implicit grid</dfn>.
	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 <a>grid items</a>
	without an explicit position.
	Once the <a>explicit grid</a> is filled
	(or if there is no <a>explicit grid</a>)
	auto-placement will also cause the generation of <a>implicit grid tracks</a>.

	The 'grid' <a>shorthand</a> property can set the <dfn>implicit grid properties</dfn>
	('grid-auto-flow', 'grid-auto-rows', and 'grid-auto-columns')
	together with the <a>explicit grid properties</a>
	in a single declaration.



<!--
   ███    ██     ██ ████████  ███████        ████████ ████████     ███     ██████  ██    ██  ██████
  ██ ██   ██     ██    ██    ██     ██          ██    ██     ██   ██ ██   ██    ██ ██   ██  ██    ██
 ██   ██  ██     ██    ██    ██     ██          ██    ██     ██  ██   ██  ██       ██  ██   ██
██     ██ ██     ██    ██    ██     ██          ██    ████████  ██     ██ ██       █████     ██████
█████████ ██     ██    ██    ██     ██          ██    ██   ██   █████████ ██       ██  ██         ██
██     ██ ██     ██    ██    ██     ██          ██    ██    ██  ██     ██ ██    ██ ██   ██  ██    ██
██     ██  ███████     ██     ███████           ██    ██     ██ ██     ██  ██████  ██    ██  ██████
-->

<h3 id='auto-tracks'>
Implicit Track Sizing: the 'grid-auto-rows' and 'grid-auto-columns' properties</h3>

	<pre class='propdef'>
	Name: grid-auto-columns, grid-auto-rows
	Value: <<track-size>>+
	Initial: auto
	Applies to: <a>grid containers</a>
	Inherited: no
	Percentages: see [[#track-sizing|Track Sizing]]
	Computed value: see [[#track-sizing|Track Sizing]]
	Animation type: if the list lengths match, by computed value type per item; discrete otherwise
	</pre>

	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 <a>implicit grid track</a> before the <a>explicit grid</a>
	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.

	<div class="example">
		<pre class="lang-html">
			&lt;style>
				#grid {
					display: grid;
					grid-template-columns: 20px;
					grid-auto-columns: 40px;
					grid-template-rows: 20px;
					grid-auto-rows: 40px;
				}
				#A { grid-column: 1; grid-row: 1; }
				#B { grid-column: 2; grid-row: 1; }
				#C { grid-column: 1; grid-row: 2; }
				#D { grid-column: 2; grid-row: 2; }
			&lt;/style>

			&lt;div id="grid">
				&lt;div id="A">A&lt;/div>
				&lt;div id="B">B&lt;/div>
				&lt;div id="C">C&lt;/div>
				&lt;div id="D">D&lt;/div>
			&lt;/div>
		</pre>

		<figure>
			<img src="images/auto-flow.svg" alt="" width=530 height=530>
			<figcaption>
				A 2&times;2 grid with
				one explicit 20px&times;20px grid cell in the first row+column
				and three additional cells resulting from
				the implicit 40px column and row generated
				to hold the additional grid items.
			</figcaption>
		</figure>
	</div>

<!--
 ██████   ████████  ████ ████████             ███    ██     ██ ████████  ███████          ████████ ██        ███████  ██      ██
██    ██  ██     ██  ██  ██     ██           ██ ██   ██     ██    ██    ██     ██         ██       ██       ██     ██ ██  ██  ██
██        ██     ██  ██  ██     ██          ██   ██  ██     ██    ██    ██     ██         ██       ██       ██     ██ ██  ██  ██
██   ████ ████████   ██  ██     ██ ███████ ██     ██ ██     ██    ██    ██     ██ ███████ ██████   ██       ██     ██ ██  ██  ██
██    ██  ██   ██    ██  ██     ██         █████████ ██     ██    ██    ██     ██         ██       ██       ██     ██ ██  ██  ██
██    ██  ██    ██   ██  ██     ██         ██     ██ ██     ██    ██    ██     ██         ██       ██       ██     ██ ██  ██  ██
 ██████   ██     ██ ████ ████████          ██     ██  ███████     ██     ███████          ██       ████████  ███████   ███  ███
-->

<h3 id="grid-auto-flow-property">
<dfn lt="auto-placement|automatic placement">Automatic Placement</dfn>: the 'grid-auto-flow' property</h3>

	<pre class='propdef'>
	Name: grid-auto-flow
	Value: [ row | column ] || dense
	Initial: row
	Applies to: <a>grid containers</a>
	Inherited: no
	Percentages: n/a
	Computed value: specified keyword(s)
	Animation type: discrete
	</pre>

	<a>Grid items</a> that aren't explicitly placed are automatically placed
	into an unoccupied space in the <a>grid container</a>
	by the <a>auto-placement algorithm</a>.
	'grid-auto-flow' controls how the <a>auto-placement algorithm</a> works,
	specifying exactly how auto-placed items get flowed into the grid.
	See [[#auto-placement-algo]] for details on precisely how the auto-placement algorithm works.

	<dl dfn-for="grid-auto-flow" dfn-type=value>
		<dt><dfn>row</dfn>
		<dd>
			The <a>auto-placement algorithm</a> places items
			by filling each row in turn,
			adding new rows as necessary.
			If neither ''row'' nor ''column'' is provided,
			''row'' is assumed.

		<dt><dfn>column</dfn>
		<dd>
			The <a>auto-placement algorithm</a> places items
			by filling each column in turn,
			adding new columns as necessary.

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

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

	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 <a>grid items</a> in <a>order-modified document order</a>.

	<div class='example'>
		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 ''grid-auto-flow/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 <a>grid item</a>.

		<div class="figure">
				<img alt="Image: A form arranged using automatic placement." src="images/auto-placed-form.png">

			<p class="caption">A form arranged using automatic placement.
		</div>

		<pre>
			&lt;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;
			}
			&lt;/style>
			&lt;form>
				&lt;label for="firstname">First name:&lt;/label>
				&lt;input type="text" id="firstname" name="firstname">
				&lt;label for="lastname">Last name:&lt;/label>
				&lt;input type="text" id="lastname" name="lastname">
				&lt;label for="address">Address:&lt;/label>
				&lt;input type="text" id="address" name="address">
				&lt;label for="address2">Address 2:&lt;/label>
				&lt;input type="text" id="address2" name="address2">
				&lt;label for="city">City:&lt;/label>
				&lt;input type="text" id="city" name="city">
				&lt;label for="state">State:&lt;/label>
				&lt;select type="text" id="state" name="state">
					&lt;option value="WA">Washington&lt;/option>
				&lt;/select>
				&lt;label for="zip">Zip:&lt;/label>
				&lt;input type="text" id="zip" name="zip">

				&lt;div id="department-block">
					&lt;label for="department">Department:&lt;/label>
					&lt;select id="department" name="department" multiple>
						&lt;option value="finance">Finance&lt;/option>
						&lt;option value="humanresources">Human Resources&lt;/option>
						&lt;option value="marketing">Marketing&lt;/option>
					&lt;/select>
				&lt;/div>

				&lt;div id="buttons">
					&lt;button id="cancel">Cancel&lt;/button>
					&lt;button id="back">Back&lt;/button>
					&lt;button id="next">Next&lt;/button>
				&lt;/div>
			&lt;/form>
		</pre>
	</div>

<!--
 ██████   ████████  ████ ████████
██    ██  ██     ██  ██  ██     ██
██        ██     ██  ██  ██     ██
██   ████ ████████   ██  ██     ██
██    ██  ██   ██    ██  ██     ██
██    ██  ██    ██   ██  ██     ██
 ██████   ██     ██ ████ ████████
-->

<h3 id='grid-shorthand'>
Grid Definition Shorthand: the 'grid' property</h3>

	<pre class='propdef shorthand'>
	Name: grid
	Value: <<'grid-template'>> |
	Value: <nobr><<'grid-template-rows'>> / [ auto-flow && dense? ] <<'grid-auto-columns'>>?</nobr> |
	Value: <nobr>[ auto-flow && dense? ] <<'grid-auto-rows'>>? / <<'grid-template-columns'>></nobr>
	Initial: none
	Applies to: <a>grid containers</a>
	</pre>

	The 'grid' property is a <a>shorthand</a> 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 <a>gutter</a> properties.)

	Its syntax matches 'grid-template',
	plus an additional syntax form
	for defining auto-flow grids:

	<dl dfn-for=grid dfn-type=value>
		<dt><<'grid-template'>>
		<dd>
			Sets the 'grid-template' longhands as as for 'grid-template',
			and the 'grid-auto-*' longhands to their initial values.

		<dt><dfn id='grid-s-auto-row'><<'grid-template-rows'>> / [ auto-flow && dense? ] <<'grid-auto-columns'>>?</dfn>
		<dt><dfn id='grid-s-auto-column'>[ auto-flow && dense? ] <<'grid-auto-rows'>>? / <<'grid-template-columns'>></dfn>
		<dd>
			Sets up auto-flow,
			by setting the tracks in one axis explicitly
			(setting either 'grid-template-rows' or 'grid-template-columns' as specified,
			and setting the other to ''grid-template-rows/none''),
			and specifying how to auto-repeat the tracks in the other axis
			(setting either 'grid-auto-rows' or 'grid-auto-columns' as specified,
			and setting the other to ''grid-auto-rows/auto'').
			'grid-auto-flow' is also set to either ''row'' or ''column'' accordingly,
			with ''dense'' if it's specified.

			All other 'grid' <a>sub-properties</a> are reset to their initial values.
	</dl>

	Note: Note that you can only specify the explicit <em>or</em> 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 <a>shorthands</a>.

	<div class='example'>
		In addition to accepting the 'grid-template' shorthand syntax for setting up the <a>explicit grid</a>,
		the 'grid' shorthand can also easily set up parameters for an auto-formatted grid.
		For example, ''grid: auto-flow 1fr / 100px;'' is equivalent to

		<pre>
			grid-template: none / 100px;
			grid-auto-flow: row;
			grid-auto-rows: 1fr;
			grid-auto-columns: auto;
		</pre>

		Similarly, ''grid: none / auto-flow 1fr'' is equivalent to
		<pre>
			grid-template: none;
			grid-auto-flow: column;
			grid-auto-rows: auto;
			grid-auto-columns: 1fr;
		</pre>
	</div>

	When serializing,
	if all the 'grid-auto-*' longhands have their initial values,
	the 'grid-template' syntax is used.


<!--
████████  ██          ███     ██████  ████ ██    ██  ██████
██     ██ ██         ██ ██   ██    ██  ██  ███   ██ ██    ██
██     ██ ██        ██   ██  ██        ██  ████  ██ ██
████████  ██       ██     ██ ██        ██  ██ ██ ██ ██   ████
██        ██       █████████ ██        ██  ██  ████ ██    ██
██        ██       ██     ██ ██    ██  ██  ██   ███ ██    ██
██        ████████ ██     ██  ██████  ████ ██    ██  ██████
-->

<h2 id="placement">
Placing Grid Items</h2>

	Every <a>grid item</a> is associated with a <a>grid area</a>,
	a rectangular set of adjacent <a>grid cells</a> that the <a>grid item</a> occupies.
	This <a>grid area</a> defines the <a>containing block</a> for the <a>grid item</a>
	within which the self-alignment properties ('justify-self' and 'align-self') determine their actual position.
	The cells that a <a>grid item</a> occupies also influence the sizing of the grid's rows and columns,
	defined in [[#layout-algorithm]].

	The location of a <a>grid item’s</a> <a>grid area</a> within the <a>grid</a>
	is defined by its <dfn export lt="grid placement" local-lt="placement">placement</dfn>,
	which consists of a <a>grid position</a> and a <a>grid span</a>:

	<dl export>
		<dt><dfn export local-lt="position|row position|column position">grid position</dfn>
		<dd>
			The <a>grid item</a>’s location in the <a>grid</a> in each axis.
			A <a>grid position</a> can be either
			<dfn export lt="definite grid position|definite row position|definite column position|definite position">definite</dfn> (explicitly specified)
			or <dfn export lt="automatic grid position|automatic row position|automatic column position|automatic position">automatic</dfn> (determined by <a>auto-placement</a>).

		<dt><dfn export local-lt="span|row span|column span">grid span</dfn>
		<dd>
			How many <a>grid tracks</a> the <a>grid item</a> occupies in each axis.
			The [=grid span=] in an axis can be [=implicit grid span|implicit=], [=explicit grid span|explicit=], or [=automatic grid span|automatic=]:

			* If both the '*-start' and '*-end' values
				of its <a>grid-placement properties</a> specify a line,
				its [=grid span=] is <dfn export lt="implicit grid span|implicit row span|implicit column span|implicit span">implicit</dfn>.
			* If it has an explicit ''grid-row-start/span'' value,
				its [=grid span=] is <dfn export lt="explicit grid span|explicit row span|explicit column span|explicit span">explicit</dfn>.
			* Otherwise, its [=grid span=] is <dfn export lt="automatic grid span|automatic row span|automatic column span|automatic span">automatic</dfn>:
				if it is [=subgridded=] in that axis,
				its [=grid span=] is <a href="#subgrid-span">determined</a> from its <<line-name-list>>;
				otherwise its [=grid span=] is 1.
	</dl>

	The <dfn export lt="grid-placement property">grid-placement properties</dfn>--
	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 <a>grid item</a>’s <a>placement</a>
	by providing any (or none) of the following six pieces of information:

	<table class=data style="width: auto">
		<thead>
			<tr>
				<td>
				<th>Row
				<th>Column
		<tbody>
			<tr>
				<th>|Start|
				<td>row-start line
				<td>column-start line
			<tr>
				<th>|End|
				<td>row-end line
				<td>column-end line
			<tr>
				<th>|Span|
				<td>row span
				<td>column span
	</table>

	A definite value for any two of <var>Start</var>, <var>End</var>, and <var>Span</var> in a given dimension implies a definite value for the third.



<h3 id='common-uses'>
Common Patterns for Grid Placement</h3>

	<em>This section is informative.</em>

	The <a>grid-placement property</a> longhands are organized into three shorthands:

	<table class=data id="grid-property-breakdown">
		<tr>
			<td colspan=4>'grid-area'
		<tr>
			<td colspan=2>'grid-column'
			<td colspan=2>'grid-row'
		<tr>
			<td>'grid-column-start'
			<td>'grid-column-end'
			<td>'grid-row-start'
			<td>'grid-row-end'
	</table>

<h4 id='common-uses-named-areas'>
Named Areas</h4>

	An item can be placed into a <a>named grid area</a>
	(such as those produced by the template in 'grid-template-areas')
	by specifying the area’s name in 'grid-area':

	<div class='example'>
		<pre>
			article {
				grid-area: main;
				/* Places item into the named area "main". */
			}
		</pre>
	</div>

	An item can also be <em>partially</em> aligned with a <a>named grid area</a>,
	with other edges aligned to some other line:

	<div class='example'>
		<pre>
			.one {
				grid-row-start: main;
				/* Align the row-start edge to the start edge of the "main" named area. */
			}
		</pre>
	</div>

<h4 id='common-uses-numeric'>
Numeric Indexes and Spans</h4>

	Grid items can be positioned and sized by number,
	which is particularly helpful for script-driven layouts:

	<div class='example'>
		<pre>
			.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; */
			}
		</pre>
	</div>

	By default, a grid item has a span of 1.
	Different spans can be given explicitly:

	<div class='example'>
		<pre>
			.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;
				/* <em>Ends</em> in the 7th row,
				   spans 5 rows up (starting in the 2nd row). */
			}
		</pre>
	</div>

	Note: Note that grid indexes are <a>writing mode</a> relative.
	For example, in a right-to-left language like Arabic,
	the first column is the rightmost column.

<h4 id='common-uses-named-lines'>
Named Lines and Spans</h4>

	Instead of counting lines by number,
	lines can be referenced by their [=line name=]:

	<div class='example'>
		<pre>
			.five {
				grid-column: first / middle;
				/* Span from line "first" to line "middle". */
			}
		</pre>
	</div>

	Note: Note that if a <a>named grid area</a> has the same name as a [=line name=],
	the placement algorithm will prefer to use <a>named grid area</a>’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:

	<div class='example'>
		<pre>
			.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. */
			}
		</pre>
	</div>

<h4 id='common-uses-auto-placement'>
Auto Placement</h4>

	A <a>grid item</a> can be automatically placed into the next available empty <a>grid cell</a>,
	growing the <a>grid</a> if there's no space left.

	<div class='example'>
		<pre>
			.eight {
				grid-area: auto; /* Initial value */
			}
		</pre>
	</div>

	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:

	<div class='example'>
		<pre>
			.nine {
				grid-area: span 2 / span 3;
				/* Auto-placed item, covering two rows and three columns. */
			}
		</pre>
	</div>

	Whether the <a>auto-placement algorithm</a> searches across and adds rows,
	or searches across and adds columns,
	is controlled by the 'grid-auto-flow' property.

	Note: By default, the <a>auto-placement algorithm</a> 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'.

<h3 id="placement-a11y">
Grid Item Placement vs. Source Order</h3>

	<blockquote>
		<p>“With great power comes great responsibility.”
	</blockquote>

	The abilities of the <a>grid-placement properties</a>
	allow content to be freely arranged and reordered within the <a>grid</a>,
	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 <a>media queries</a>.
	However <strong>they are not a substitute for correct source ordering</strong>.

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


<!--
 ██████   ████████  ████ ████████          ████████   ███████  ██      ██          ██████  ████████    ███    ████████  ████████
██    ██  ██     ██  ██  ██     ██         ██     ██ ██     ██ ██  ██  ██         ██    ██    ██      ██ ██   ██     ██    ██
██        ██     ██  ██  ██     ██         ██     ██ ██     ██ ██  ██  ██         ██          ██     ██   ██  ██     ██    ██
██   ████ ████████   ██  ██     ██ ███████ ████████  ██     ██ ██  ██  ██ ███████  ██████     ██    ██     ██ ████████     ██
██    ██  ██   ██    ██  ██     ██         ██   ██   ██     ██ ██  ██  ██               ██    ██    █████████ ██   ██      ██
██    ██  ██    ██   ██  ██     ██         ██    ██  ██     ██ ██  ██  ██         ██    ██    ██    ██     ██ ██    ██     ██
 ██████   ██     ██ ████ ████████          ██     ██  ███████   ███  ███           ██████     ██    ██     ██ ██     ██    ██
-->

<h3 id='line-placement'>
Line-based Placement: the 'grid-row-start', 'grid-column-start', 'grid-row-end', and 'grid-column-end' properties</h3>

	<pre class='propdef'>
	Name: grid-row-start, grid-column-start, grid-row-end, grid-column-end
	Value: <<grid-line>>
	Initial: auto
	Applies to: <a>grid items</a> and absolutely-positioned boxes whose containing block is a <a>grid container</a>
	Inherited: no
	Percentages: n/a
	Computed value: specified keyword, identifier, and/or integer
	Animation type: discrete
	</pre>

	<pre class=prod>
		<dfn for="grid-row-start, grid-column-start, grid-row-end, grid-column-end"><<grid-line>></dfn> =
		  auto |
		  <<custom-ident>> |
		  [ [ <<integer [-∞,-1]>> | <<integer [1,∞]>> ] && <<custom-ident>>? ] |
		  [ span &amp;&amp; [ <<integer [1,∞]>> || <<custom-ident>> ] ]
	</pre>

	The 'grid-row-start', 'grid-column-start', 'grid-row-end', and 'grid-column-end' properties
	determine a <a>grid item</a>’s size and location within the <a>grid</a>
	by contributing a line, a span, or nothing (automatic)
	to its <a>grid placement</a>,
	thereby specifying the <a>inline-start</a>, <a>block-start</a>, <a>inline-end</a>, and <a>block-end</a> edges of its <a>grid area</a>.

	Values have the following meanings:

	<dl dfn-for="<grid-line>" dfn-type=value>
		<dt><dfn id='grid-placement-slot'><<custom-ident>></dfn>
		<dd>
			First attempt to match the <a>grid area</a>’s edge to a <a>named grid area</a>:
			if there is a [=grid line=] whose [=line name=] is <css><<custom-ident>>-start</css> (for 'grid-*-start') / <css><<custom-ident>>-end</css> (for 'grid-*-end'),
			contributes the first such line to the <a>grid item</a>’s <a>placement</a>.

			Note: <a>Named grid areas</a> automatically generate [=implicitly-assigned line names=] of this form,
			so specifying ''grid-row-start: foo'' will choose the start edge of that <a>named grid area</a>
			(unless another line named ''foo-start'' was explicitly specified before it).

			Otherwise,
			treat this as if the integer ''1'' had been specified along with the <<custom-ident>>.

		<dt><dfn id='grid-placement-int'>[ <<integer [-∞,-1]>> | <<integer [1,∞]>> ] && <<custom-ident>>?</dfn>
		<dd>
			Contributes the <var>N</var>th <a>grid line</a> to the <a>grid item</a>’s <a>placement</a>.
			If a negative integer is given,
			it instead counts in reverse,
			starting from the end edge of the <a>explicit grid</a>.

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

			An <<integer>> value of zero makes the declaration invalid.

		<dt><dfn id='grid-placement-span-int'>span && [ <<integer [1,∞]>> || <<custom-ident>> ]</dfn>
		<dd>
			Contributes a <a>grid span</a> to the <a>grid item</a>’s <a>placement</a>
			such that the corresponding edge of the <a>grid item</a>’s <a>grid area</a> is <var>N</var> lines from its opposite edge
			in the corresponding direction.
			For example, ''grid-column-end: span 2'' indicates the second grid line in the endward direction
			from the 'grid-column-start' line.

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

			<div class="example">
				For example, given the following declarations:

				<pre class="lang-css">
				.grid { grid-template-columns: 100px; }
				.griditem { grid-column: span foo / 4; }
				</pre>

				The <a>grid container</a> has an <a>explicit grid</a> with two grid lines,
				numbered 1 and 2.
				The <a>grid item's</a> column-end edge is specified to be at line 4,
				so two lines are generated in the endward side of the <a>implicit grid</a>.

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

				<figure>
					<img src="images/implicit-lines-search.svg" width=600>
					<figcaption>An illustration of the result.</figcaption>
				</figure>
			</div>

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

		<dt><dfn id='grid-placement-auto'>auto</dfn>
		<dd>
			The property contributes nothing to the <a>grid item</a>’s <a>placement</a>,
			indicating <a>auto-placement</a> or a default span of one.
			(See [[#placement]], above.)
	</dl>

	In all the above productions,
	the <<custom-ident>> additionally excludes the keywords <css>span</css> and <css>auto</css>.

	<div class='example'>
			Given a single-row, 8-column grid and the following 9 named lines:

		<pre>
			1  2  3  4  5  6  7  8  9
			+--+--+--+--+--+--+--+--+
			|  |  |  |  |  |  |  |  |
			A  B  C  A  B  C  A  B  C
			|  |  |  |  |  |  |  |  |
			+--+--+--+--+--+--+--+--+
		</pre>

			The following declarations place the grid item between the lines indicated by index:

		<pre>
			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 */
		</pre>
	</div>

<h4 id='grid-placement-errors'>
Grid Placement Conflict Handling</h4>

	If the <a>placement</a> for a <a>grid item</a> contains two lines,
	and the <a>start</a> line is further end-ward than the <a>end</a> line,
	swap the two lines.
	If the <a>start</a> line is <em>equal</em> to the <a>end</a> line,
	remove the <a>end</a> line.

	If the <a>placement</a> contains two spans,
	remove the one contributed by the <a>end</a> <a>grid-placement property</a>.

	If the <a>placement</a> contains only a span for a named line,
	replace it with a span of 1.

<!--
 ██████   ████████  ████ ████████           ██████   ███████  ██       ██     ██ ██     ██ ██    ██
██    ██  ██     ██  ██  ██     ██         ██    ██ ██     ██ ██       ██     ██ ███   ███ ███   ██
██        ██     ██  ██  ██     ██         ██       ██     ██ ██       ██     ██ ████ ████ ████  ██
██   ████ ████████   ██  ██     ██ ███████ ██       ██     ██ ██       ██     ██ ██ ███ ██ ██ ██ ██
██    ██  ██   ██    ██  ██     ██         ██       ██     ██ ██       ██     ██ ██     ██ ██  ████
██    ██  ██    ██   ██  ██     ██         ██    ██ ██     ██ ██       ██     ██ ██     ██ ██   ███
 ██████   ██     ██ ████ ████████           ██████   ███████  ████████  ███████  ██     ██ ██    ██
-->

<h3 id='placement-shorthands'>
Placement Shorthands: the 'grid-column', 'grid-row', and 'grid-area' properties</h3>

	<pre class='propdef shorthand'>
	Name: grid-row, grid-column
	Value: <<grid-line>> [ / <<grid-line>> ]?
	Initial: auto
	Applies to: <a>grid items</a> and absolutely-positioned boxes whose containing block is a <a>grid container</a>
	Inherited: no
	Percentages: N/A
	Animation type: discrete
	</pre>

	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 <a value for="<grid-line>">auto</a>.

	<pre class='propdef shorthand'>
	Name: grid-area
	Value: <<grid-line>> [ / <<grid-line>> ]{0,3}
	Initial: auto
	Applies to: <a>grid items</a> and absolutely-positioned boxes whose containing block is a <a>grid container</a>
	Inherited: no
	Percentages: N/A
	Animation type: discrete
	</pre>

	The 'grid-area' property is a <a>shorthand</a> 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 <a value for="<grid-line>">auto</a>.

	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 <a value for="<grid-line>">auto</a>.

	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 <a value for="<grid-line>">auto</a>.

	Note: The resolution order for this shorthand is row-start/column-start/row-end/column-end,
	which goes <abbr title="counterclockwise">CCW</abbr> for <abbr title="left-to-right">LTR</abbr> pages,
	the opposite direction of the related 4-edge properties using physical directions, like 'margin'.

<!--
   ███    ██     ██ ████████  ███████          ████████  ██          ███     ██████  ████████ ██     ██ ████████ ██    ██ ████████
  ██ ██   ██     ██    ██    ██     ██         ██     ██ ██         ██ ██   ██    ██ ██       ███   ███ ██       ███   ██    ██
 ██   ██  ██     ██    ██    ██     ██         ██     ██ ██        ██   ██  ██       ██       ████ ████ ██       ████  ██    ██
██     ██ ██     ██    ██    ██     ██ ███████ ████████  ██       ██     ██ ██       ██████   ██ ███ ██ ██████   ██ ██ ██    ██
█████████ ██     ██    ██    ██     ██         ██        ██       █████████ ██       ██       ██     ██ ██       ██  ████    ██
██     ██ ██     ██    ██    ██     ██         ██        ██       ██     ██ ██    ██ ██       ██     ██ ██       ██   ███    ██
██     ██  ███████     ██     ███████          ██        ████████ ██     ██  ██████  ████████ ██     ██ ████████ ██    ██    ██
-->

<h3 id='auto-placement-algo'>
Grid Item Placement Algorithm</h3>

	The following <dfn export local-lt="auto-placement algorithm">grid item placement algorithm</dfn>
	resolves <a>automatic positions</a> of <a>grid items</a> into <a>definite positions</a>,
	ensuring that every <a>grid item</a> has a well-defined <a>grid area</a> to lay out into.
	(<a>Grid spans</a> 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 <a>implicit grid</a>,
	if there is no room in the <a>explicit grid</a> to place an auto-positioned <a>grid item</a>.

	Every <a>grid cell</a>
	(in both the <a>explicit</a> and <a>implicit grids</a>)
	can be <dfn>occupied</dfn> or <dfn>unoccupied</dfn>.
	A cell is <a>occupied</a>
	if it's covered by the <a>grid area</a>
	of a <a>grid item</a> with a <a>definite grid position</a>;
	otherwise,
	the cell is <a>unoccupied</a>.
	A cell's <a>occupied</a>/<a>unoccupied</a> status can change during this algorithm.

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

	Note: The <a>auto-placement algorithm</a> works with the <a>grid items</a> in <a>order-modified document order</a>,
	not their original document order.

	0. <strong>Generate anonymous grid items</strong>
		as described in [[#grid-items]].
		(Anonymous <a>grid items</a> are always auto-placed,
		since their boxes can't have any <a>grid-placement properties</a> specified.)

	1. <strong>Position anything that's not auto-positioned.</strong>

	2. <strong>Process the items locked to a given row.</strong>

		For each <a>grid item</a> with a <a>definite row position</a>
		(that is, the 'grid-row-start' and 'grid-row-end' properties define a <a>definite grid position</a>),
		in <a>order-modified document order</a>:

		: “sparse” packing (default behavior)
		::
			Set the column-start line of its <a>placement</a>
			to the earliest (smallest positive index) line index
			that ensures this item’s <a>grid area</a> will not overlap any <a>occupied</a> grid cells
			and that is past any <a>grid items</a> previously placed in this row by this step.

		: “dense” packing (''dense'' specified)
		::
			Set the column-start line of its <a>placement</a>
			to the earliest (smallest positive index) line index
			that ensures this item’s <a>grid area</a> will not overlap any <a>occupied</a> grid cells.

	3. <strong>Determine the columns in the implicit grid.</strong>

		Create columns in the <a>implicit grid</a>:

		1. Start with the columns from the <a>explicit grid</a>.
		2. Among all the items with a <a>definite column position</a>
			(explicitly positioned items, items positioned in the previous step, and items not yet positioned but with a definite column)
			add columns to the beginning and end of the <a>implicit grid</a>
			as necessary to accommodate those items.
		3. If the largest <a>column span</a> among all the items <em>without</em> a <a>definite column position</a>
			is larger than the width of the <a>implicit grid</a>,
			add columns to the end of the <a>implicit grid</a> to accommodate that <a>column span</a>.

		<div class='example'>
			For example, in the following style fragment:

			<pre>
				#grid {
					display: grid;
					grid-template-columns: repeat(5, 100px);
					grid-auto-flow: row;
				}
				#grid-item {
					grid-column: 4 / span 3;
				}
			</pre>

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

	4. <strong>Position the remaining grid items.</strong>

		The <dfn export local-lt="cursor">auto-placement cursor</dfn> defines the current “insertion point” in the grid,
		specified as a pair of row and column <a>grid lines</a>.
		Initially the <a>auto-placement cursor</a> is set to the start-most row and column lines in the <a>implicit grid</a>.

		The 'grid-auto-flow' value in use determines how to position the items:

		: “sparse” packing (default behavior)
		:: For each <a>grid item</a> that hasn't been positioned by the previous steps,
			in <a>order-modified document order</a>:

			: If the item has a <a>definite column position</a>:
			::
				1. Set the column position of the <a>cursor</a> to the <a>grid item’s</a> column-start line.
					If this is less than the previous column position of the <a>cursor</a>,
					increment the row position by 1.
				2. Increment the <a>cursor</a>’s row position until a value is found
					where the <a>grid item</a> does not overlap any <a>occupied</a> grid cells
					(creating new rows in the <a>implicit grid</a> as necessary).
				3. Set the item's row-start line to the <a>cursor's</a> row position,
					and set the item's row-end line according to its span from that position.

			: If the item has an <a>automatic grid position</a> in both axes:
			::
				1. Increment the column position of the <a>auto-placement cursor</a>
					until either this item’s <a>grid area</a> does not overlap any <a>occupied</a> grid cells,
					or the <a>cursor's</a> column position,
					plus the item's column span,
					overflow the number of columns in the implicit grid,
					as determined earlier in this algorithm.
				2. If a non-overlapping position was found in the previous step,
					set the item's row-start and column-start lines to the <a>cursor's</a> position.
					Otherwise,
					increment the <a>auto-placement cursor</a>’s row position
					(creating new rows in the <a>implicit grid</a> as necessary),
					set its column position to the start-most column line in the <a>implicit grid</a>,
					and return to the previous step.

		: “dense” packing (''dense'' specified)
		:: For each <a>grid item</a> that hasn't been positioned by the previous steps,
			in <a>order-modified document order</a>:

			: If the item has a <a>definite column position</a>:
			::
				1. Set the row position of the cursor to the start-most row line in the <a>implicit grid</a>.
					Set the column position of the cursor to the <a>grid item’s</a> column-start line.
				2. Increment the <a>auto-placement cursor</a>’s row position until a value is found
					where the <a>grid item</a> does not overlap any <a>occupied</a> grid cells
					(creating new rows in the <a>implicit grid</a> as necessary).
				3. Set the item's row-start line index to the <a>cursor's</a> row position.
					(Implicitly setting the item's row-end line according to its span, as well.)

			: If the item has an <a>automatic grid position</a> in both axes:
			::
				1. Set the cursor's row and column positions to start-most row and column lines in the <a>implicit grid</a>.
				2. Increment the column position of the <a>auto-placement cursor</a>
					until either this item’s <a>grid area</a> does not overlap any <a>occupied</a> grid cells,
					or the <a>cursor's</a> column position,
					plus the item's column span,
					overflow the number of columns in the implicit grid,
					as determined earlier in this algorithm.
				3. If a non-overlapping position was found in the previous step,
					set the item's row-start and column-start lines to the <a>cursor's</a> position.
					Otherwise,
					increment the <a>auto-placement cursor</a>’s row position
					(creating new rows in the <a>implicit grid</a> as necessary),
					reset its column position to the start-most column line in the <a>implicit grid</a>,
					and return to the previous step.

<!--
 ██████  ██     ██ ████████   ██████   ████████  ████ ████████
██    ██ ██     ██ ██     ██ ██    ██  ██     ██  ██  ██     ██
██       ██     ██ ██     ██ ██        ██     ██  ██  ██     ██
 ██████  ██     ██ ████████  ██   ████ ████████   ██  ██     ██
      ██ ██     ██ ██     ██ ██    ██  ██   ██    ██  ██     ██
██    ██ ██     ██ ██     ██ ██    ██  ██    ██   ██  ██     ██
 ██████   ███████  ████████   ██████   ██     ██ ████ ████████
-->

<h2 id="subgrids">
Subgrids</h2>

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

	<ul style="list-style-type: lower-alpha">
		<li id="subgrid-tracks">
			Placing the <a>subgrid</a>
			creates a correspondence between its [=subgridded=] tracks
			and those that it spans in its [=parent grid=].
			The grid lines thus shared between the [=subgrid=] and its parent
			form the subgrid’s <a>explicit grid</a>,
			and its track sizes are governed by the [=parent grid=].

		<li id="subgrid-span">
			The number of explicit tracks in the <a>subgrid</a>
			in a [=subgridded=] dimension
			always corresponds to the number of <a>grid tracks</a>
			that it spans in its parent <a>grid</a>:

			<ul>
				<li>
					If the <a>subgrid</a>’s <a>grid span</a> in the subgridded dimension is [=explicit grid span|explicit=] or [=implicit grid span|implicit=],
					then the number of explicit tracks in each subgridded dimension
					is taken from its used <a>grid span</a> in that dimension
					(regardless of its 'grid-template-*' properties).

				<li>
					If it has an [=automatic grid span=],
					then its used <a>grid span</a> is taken
					from the number of explicit tracks specified for that axis
					by its 'grid-template-*' properties,
					floored at one.
			</ul>

			Note: The explicit grid determined here can be further truncated
			if the placement of the [=subgrid=] is clamped by its parent grid.
			See <a href="#subgrid-implicit">the "no implicit tracks" bullet point</a>.

			If the 'grid-template-*' properties specify a <<line-name-list>>
			in a [=subgridded axis=],
			the used value is truncated
			to match the used number of explicit tracks.

		<li id="subgrid-indexing">
			The <a>grid-placement properties</a> of the <a>subgrid</a>’s <a>grid items</a>
			and the line numbers they use
			are scoped to the lines covered by the [=subgrid=],
			exactly consistent with the lines outside the [=subgrid=]
			being excluded from its <a>explicit grid</a>.
			E.g. numeric indices count starting from the first line of the [=subgrid=]
			rather than the first line of the [=parent grid=].

			Line numbering and placement rules
			obey the [=subgrid=]’s own <a>writing mode</a>,
			just as they would for a nested independent grid.

		<li id="subgrid-line-name-inheritance">
			Since <a>subgrids</a> can be placed before their contents are placed,
			the [=subgridded=] lines
			automatically receive the [=explicitly-assigned line names=]
			specified on the corresponding lines of the parent <a>grid</a>.

			These names are in <em>addition</em> to
			any [=line names=] specified locally on the [=subgrid=].

		<li id="subgrid-area-inheritance">
			When a <a>subgrid</a> overlaps a <a>named grid area</a> in its parent
			that was created by a 'grid-template-areas' property declaration,
			[=implicitly-assigned line names=] are assigned
			to represent the parent’s <a>named grid area</a>
			within the <a>subgrid</a>.

			Note: If a <a>named grid area</a>
			only partially overlaps the <a>subgrid</a>,
			its [=implicitly-assigned line names=]
			will be assigned
			to the first and/or last line of the <a>subgrid</a>
			such that a <a>named grid area</a> exists
			representing that partially overlapped area of the <a>subgrid</a>;
			thus the [=line name=] assignments of the <a>subgrid</a>
			might not always correspond exactly
			to the [=line name=] assignments of the parent <a>grid</a>.

			These names are also in <em>addition</em> to
			any [=line names=] specified locally on the [=subgrid=].

			<div class="example">
				In the following example,
				the 4-column grand-parent grid has both explicit line names
				and implicit ones generated by 'grid-template-areas':

				<xmp>
					<style type="css">
					  .outer {
					    display: grid;
					    grid-template-columns:
					      [outer-edge] 20px [main-start] 1fr [center] 1fr max-content [main-end];
					    grid-template-areas:
					      "gutter info info photos";
					  }
					  .middle {
					    grid-column: main-start / main-end;
					    display: grid;
					    grid: subgrid / subgrid;
					  }
					  .inner {
					    grid-column: center / -1;
					    display: grid;
					    grid: subgrid / subgrid;
					  }
					</style>

					<div class="outer">
					  <div class="middle">
					    <div class="inner">&hellip;</div>
					  </div>
					</div>
				</xmp>

				After all types of name resolution,
				the names for each grid will be:
				<pre>
					.outer = [outer-edge gutter-start] [gutter-end info-start main-start] [center] [info-end photos-start] [main-end photos-end]
					.middle = [info-start main-start] [center] [info-end photos-start] [main-end photos-end]
					.inner = [center info-start] [info-end photos-start] [main-end photos-end]
				</pre>

				Notice that all the [=explicitly-assigned line names=]
				inherit straight through to .inner,
				but the [=implicitly-assigned line names=] are calculated based on
				each [=subgrid=]'s overlap of the original <a>named grid area</a>.
			</div>

		<li id="subgrid-implicit">
			The <a>subgrid</a> does not have any <a>implicit grid tracks</a>
			in the [=subgridded=] dimension(s).
			Hypothetical <a>implicit grid lines</a> are used to resolve placement
			as usual when the <a>explicit grid</a> does not have enough lines;
			however
			each <a>grid item</a>’s <a>grid area</a>
			is <a lt="clamp a grid area">clamped</a> to the [=subgrid=]’s <a>explicit grid</a>
			(using the same procedure as for clamping placement in an overly-large grid).

			<div class="example">
				For example, if a ''span 1'' subgrid has a <a>grid item</a> with ''grid-column: 2 / span 3;'',
				then that item is instead forced into (and limited to) the first (only) track in the subgrid.
			</div>

			Note: This means that a subgrid might have fewer tracks than it expected,
			if its parent is also a subgrid and therefore has a fixed number of tracks.
			(A subgrid might likewise have fewer tracks than expected
			because its parent is hitting the
			[[#overlarge-grids|UA limit on grid tracks]].)

		<li id="subgrid-size-contribution">
			The <a>subgrid</a> itself lays out as an ordinary <a>grid item</a> in its [=parent grid=],
			but acts as if it was completely empty for track sizing purposes
			in the [=subgridded=] dimension.

		<li id="subgrid-item-contribution">
			The <a>subgrid</a>'s own <a>grid items</a> participate
			in the sizing of its [=parent grid=] in the [=subgridded=] dimension(s)
			and are aligned to it in those dimensions.

			<p id="subgrid-margins">
			In this process, the sum of the <a>subgrid</a>'s
			margin, padding, [=scrollbar gutter=], and border at each edge
			are applied as an extra layer of (potentially negative) margin
			to the items at those edges.
			This extra layer of “margin” accumulates
			through multiple levels of [=subgrids=].

			<div class="example">
				For example, if we have a 3&times;3 grid with the following tracks:

				<pre>#parent-grid { grid-template-columns: 300px auto 300px; }</pre>

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

				<pre>
					#subgrid { grid-column: 2 / span 2; } /* cover parent's 2nd and 3rd tracks */
					#subgrid > :first-child { grid-column: 1; } /* subgrid's 1st track, parent grid's 2nd track */
				</pre>

				If the subgrid has margins/borders/padding,
				the size of those margins/borders/padding also influences sizing.
				For example, if the subgrid has 100px padding:

				<pre>#subgrid { padding: 100px; }</pre>

				Then a <a>grid item</a> in the <a>subgrid's</a> first track
				acts as if it has an additional ''100px'' of top, left, and bottom margin,
				influencing the sizing of the parent grid's tracks
				and the <a>grid item's</a> own position.
			</div>

			<p id="subgrid-gaps">
			Meanwhile,
			half the size of the difference between
			the [=subgrid=]’s <a>gutters</a> ('row-gap'/'column-gap')
			and its [=parent grid=]’s <a>gutters</a>
			is applied as an extra layer of (potentially negative) margin
			to the items not at those edges.
			This extra layer of “margin” also accumulates
			through multiple levels of [=subgrids=].
			A value of ''row-gap/normal''
			indicates that the [=subgrid=] has the same size <a>gutters</a>
			as its [=parent grid=],
			i.e. the applied difference is zero.

			Note: The end result will be that the parent’s grid tracks
			will be sized as specified,
			and that the [=subgrid=]’s [=gutters=] will visually center-align
			with the [=parent grid=]’s [=gutters=].

			<div class="example">
				<p>For example,
				suppose we have a 300px-wide outer grid
				with 50px gaps
				and its columns specified as ''100px 1fr''.
				A subgrid spanning both tracks would have&hellip;

				<dl>
					<dt>&hellip; if its 'column-gap' were ''column-gap/normal'' (or ''50px''):
					<dd>
						<ul>
							<li>A grid item in its left column
								sized and laid out
								(and contributing its size to the parent grid’s sizing calculations)
								without any special adjustment,
								thus stretching to 100px wide
								while remaining aligned
								to the subgrid’s left edge.
							<li>A grid item in its right column
								sized and laid out
								(and contributing its size to the parent grid’s sizing calculations)
								without any special adjustment,
								thus stretching to 150px wide,
								while remaining aligned
								to the subgrid’s right edge.
							<li>An effective visual <a>gutter</a> between the items
								of 50px, exactly matching its parent grid.
						</ul>

						<img src="images/subgrid-gap-normal.png" alt="">

					<dt>&hellip; if its 'column-gap' were ''0'':
					<dd>
						<ul>
							<li>A grid item in its left column
								sized and laid out
								(and contributing its size to the parent grid’s sizing calculations)
								as if it had a -25px right margin,
								thus stretching to 125px wide
								while remaining aligned
								to the subgrid’s left edge.
							<li>A grid item in its right column
								sized and laid out
								(and contributing its size to the parent grid’s sizing calculations)
								as if it had a -25px left margin,
								thus stretching to 175px wide,
								while remaining aligned
								to the subgrid’s right edge.
							<li>An effective visual <a>gutter</a> between the items
								of zero, as specified by its 'column-gap'.
						</ul>

						<img src="images/subgrid-gap-0px.png" alt="">

					<dt>&hellip; if its 'column-gap' were ''25px'':
					<dd>
						<ul>
							<li>A grid item in its left column
								sized and laid out
								(and contributing its size to the parent grid’s sizing calculations)
								as if it had a -12.5px right margin,
								thus stretching to 112.5px wide
								while remaining aligned
								to the subgrid’s left edge.
							<li>A grid item in its right column
								sized and laid out
								(and contributing its size to the parent grid’s sizing calculations)
								as if it had a -12.5px left margin,
								thus stretching to 162.5px wide,
								while remaining aligned
								to the subgrid’s right edge.
							<li>An effective visual <a>gutter</a> between the items
								of 25px, as specified by its 'column-gap'.
						</ul>

						<img src="images/subgrid-gap-25px.png" alt="">

					<dt>&hellip; if its 'column-gap' were ''75px'':
					<dd>
						<ul>
							<li>A grid item in its left column
								sized and laid out
								(and contributing its size to the parent grid’s sizing calculations)
								as if it had a 12.5px right margin,
								thus stretching to 87.5px wide
								while remaining aligned
								to the subgrid’s left edge.
							<li>A grid item in its right column
								sized and laid out
								(and contributing its size to the parent grid’s sizing calculations)
								as if it had a 12.5px left margin,
								thus stretching to 137.5px wide,
								while remaining aligned
								to the subgrid’s right edge.
							<li>An effective visual <a>gutter</a> between the items
								of 75px, as specified by its 'column-gap'.
						</ul>

						<img src="images/subgrid-gap-75px.png" alt="">
				</dl>
			</div>

		<li id="subgrid-edge-placeholders">
			For each edge of a non-empty [=subgrid=],
			to account for the subgrid’s margin/border/padding (and any scrollbar gutter) at that edge,
			a hypothetical item is contributed to the track sizing algorithm
			for each span size
			in the set of items spanning into
			the occupied track closest to that edge of the subgrid.
			The hypothetical item’s sizes are taken from the sizes of the largest such item
			of each span size,
			and are additionally inflated by the subgrid’s own margin/border/padding/gutter
			at that edge.
			Correspondingly, the hypothetical item’s span is taken
			from that same real item’s span,
			and inflated by the number of empty tracks between it
			and the relevant [=subgrid=]’s edge(s).

			Note: This step can be shortcut if
			the tracks closest to the [=subgrid=]’s edges contain real items,
			which would have already
			<a href="#subgrid-item-contribution">accounted for the subgrid’s margin/border/padding</a>
			as described above.

			<div class="example">
				For example, in the following subgrid layout:
				<pre>
					5px auto auto 5px
					.   aaaaaaaaa .
					.   bbbb cccc .
				</pre>

				Assuming subgrid items <var>a</var>, <var>b</var>, and <var ignore>c</var>
				occupying their corresponding grid areas
				and a subgrid padding of 25px,
				two hypothetical grid items would be contributed
				to the track sizing algorithm
				for the purpose of handling the subgrid’s inline-start padding:
				one with the size of <var>b</var> plus 25px,
				spanning the first two columns;
				and one with the size of <var>a</var> plus 25px,
				spanning the first three columns.
			</div>

		<li id="subgrid-box-alignment">
			The <a>subgrid</a> is always stretched in its [=subgridded=] dimension(s):
			the 'align-self'/'justify-self' properties on it are ignored,
			as are any specified width/height constraints.

		<li id="subgrid-grid-alignment">
			Layoutwise, the <a>subgrid</a>’s <a>grid</a>
			is always aligned with the corresponding section of the parent <a>grid</a>;
			the 'align-content'/'justify-content' properties on it are also ignored
			in the [=subgridded=] dimension.

		<li id="subgrid-overflow">
			The 'overflow' property does apply to <a>subgrids</a>,
			so that overflowing contents of the subgrid can be scrolled into view.
			(Note: the act of scrolling does not affect layout.)

		<li id="subgrid-relpos">
			[=Relative positioning=] applies to <a>subgrids</a> as normal,
			and shifts the box and its content together as usual.
			(Note: Relative positioning takes place after alignment,
			and does not affect track sizing.)
	</ul>

<!--
   ███    ████████   ██████  ████████   ███████   ██████
  ██ ██   ██     ██ ██    ██ ██     ██ ██     ██ ██    ██
 ██   ██  ██     ██ ██       ██     ██ ██     ██ ██
██     ██ ████████   ██████  ████████  ██     ██  ██████
█████████ ██     ██       ██ ██        ██     ██       ██
██     ██ ██     ██ ██    ██ ██        ██     ██ ██    ██
██     ██ ████████   ██████  ██         ███████   ██████
-->

<h2 id="abspos">
Absolute Positioning</h2>

<h3 id="abspos-items">
With a Grid Container as Containing Block</h3>

	If an absolutely positioned element's <a>containing block</a>
	is generated by a <a>grid container</a>,
	the containing block corresponds to the <a>grid area</a> determined by its <a>grid-placement properties</a>.
	The offset properties ('top'/'right'/'bottom'/'left')
	then indicate offsets inwards from the corresponding edges
	of this <a>containing block</a>, as normal.

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

	<div class='example'>
		<pre>
			.grid {
				grid: 1fr 1fr 1fr 1fr / 10rem 10rem 10rem 10rem;
				/* 4 equal-height rows filling the <a>grid container</a>,
				   4 columns of ''10rem'' each */
				justify-content: center;
				/* center the grid horizontally within the <a>grid container</a> */
				position: relative;
				/* Establish abspos <a>containing block</a> */
			}

			.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 */
				/* <a>Containing block</a> covers the top right quadrant of the <a>grid container</a> */

				position: absolute;
				top: 70px;
				bottom: 40px;
				left: 100px;
				right: 30px;
			}
		</pre>

		<figure>
			<img src="images/abspos-grid.svg" width="702" height="402" alt=''>
		</figure>

		Note: Grids and the <a>grid-placement properties</a> are <a>flow-relative</a>,
		while the offset properties ('left', 'right', 'top', and 'bottom') are <a>physical</a>,
		so if the 'direction' or 'writing-mode' properties change,
		the grid will transform to match,
		but the offsets won't.
	</div>

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

	Note: Thus, by default, the absolutely-positioned box's <a>containing block</a> will correspond
	to the padding edges of the <a>grid container</a>, as it does for <a>block containers</a>.

	Absolute positioning occurs after layout of the <a>grid</a> and its <a>in-flow</a> 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 <a>grid-placement property</a> refers to a non-existent line
	either by explicitly specifying such a line or by spanning outside of the existing <a>implicit grid</a>,
	it is instead treated as specifying ''auto''
	(instead of creating new <a>implicit grid lines</a>).

	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 <a>placement</a> only contains a <a>grid span</a>,
	replace it with the two ''auto'' lines in that axis.
	(This happens when both <a>grid-placement properties</a> in an axis contributed a span originally,
	and [[#grid-placement-errors]] caused the second span to be ignored.)


<h3 id="static-position">
With a Grid Container as Parent</h3>

	An absolutely-positioned child of a <a>grid container</a>
	is <a>out-of-flow</a> and not a <a>grid item</a>,
	and so does not affect the placement of other items
	or the sizing of the grid.

	The <a href="https://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width">static position</a> [[!CSS2]]
	of an absolutely-positioned child of a <a>grid container</a>
	is determined as if it were the sole grid item
	in a <a>grid area</a>
	whose edges coincide with the content edges of the <a>grid container</a>.

	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.

<!--
   ███    ██       ████  ██████   ██    ██ ██     ██ ████████ ██    ██ ████████
  ██ ██   ██        ██  ██    ██  ███   ██ ███   ███ ██       ███   ██    ██
 ██   ██  ██        ██  ██        ████  ██ ████ ████ ██       ████  ██    ██
██     ██ ██        ██  ██   ████ ██ ██ ██ ██ ███ ██ ██████   ██ ██ ██    ██
█████████ ██        ██  ██    ██  ██  ████ ██     ██ ██       ██  ████    ██
██     ██ ██        ██  ██    ██  ██   ███ ██     ██ ██       ██   ███    ██
██     ██ ████████ ████  ██████   ██    ██ ██     ██ ████████ ██    ██    ██
-->

<h2 id='alignment'>
Alignment and Spacing</h2>

	After a <a>grid container</a>’s <a>grid tracks</a> have been sized,
	and the dimensions of all <a>grid items</a> are finalized,
	<a>grid items</a> can be aligned within their <a>grid areas</a>.

	Note: The [=grid items=] of [=subgrids=] participate in alignment,
	including [=baseline alignment=],
	together with their [=parent grid=]'s items;
	see <a href="#subgrid-item-contribution">Subgrids (h)</a>.

	The 'margin' properties can be used to align items in a manner similar to
	what margins can do in block layout.
	<a>Grid items</a> also respect the <a>box alignment properties</a>
	from the <a href="http://www.w3.org/TR/css-align/">CSS Box Alignment Module</a> [[!CSS-ALIGN-3]],
	which allow easy keyword-based alignment of items in both the rows and columns.

	By default,
	<a>grid items</a> stretch to fill their <a>grid area</a>.
	However, if 'justify-self' or 'align-self' compute to a value other than ''justify-self/stretch''
	or margins are <a value for="margin">auto</a>,
	<a>grid items</a> will auto-size to fit their contents.

<!--
 ██████   ████████  ████ ████████           ██████      ███    ████████
██    ██  ██     ██  ██  ██     ██         ██    ██    ██ ██   ██     ██
██        ██     ██  ██  ██     ██         ██         ██   ██  ██     ██
██   ████ ████████   ██  ██     ██ ███████ ██   ████ ██     ██ ████████
██    ██  ██   ██    ██  ██     ██         ██    ██  █████████ ██
██    ██  ██    ██   ██  ██     ██         ██    ██  ██     ██ ██
 ██████   ██     ██ ████ ████████           ██████   ██     ██ ██
-->

<h3 id='gutters'>
Gutters: the 'row-gap', 'column-gap', and 'gap' properties</h3>

	The 'row-gap' and 'column-gap' properties
	(and their 'gap' shorthand),
	when specified on a <a>grid container</a>,
	define the [=gutters=] between <a>grid rows</a> and <a>grid columns</a>.
	Their syntax is defined in [[css-align-3#gaps]].

	The effect of these properties
	is as though the affected <a>grid lines</a> acquired thickness:
	the <a>grid track</a> between two <a>grid lines</a>
	is the space between the <a>gutters</a> that represent them.
	For the purpose of [[#algo-track-sizing|track sizing]],
	each <a>gutter</a> is treated as
	an extra, empty, fixed-size track of the specified size,
	which is spanned by any <a>grid items</a>
	that span across its corresponding <a>grid line</a>.

	Note: Additional spacing may be added between tracks
	due to 'justify-content'/'align-content'.
	See [[#algo-grid-sizing]].
	This space effectively increases the size of the <a>gutters</a>.

	If a <a>grid</a> is <a>fragmented</a> between tracks,
	the <a>gutter</a> spacing between those tracks must be suppressed.
	<span class="note">Note that gutters are suppressed even after forced breaks,
	<a href="https://www.w3.org/TR/css-break-3/#break-margins">unlike margins</a>.</span>

	<a>Gutters</a> only appear <em>between</em> tracks of the <a>implicit grid</a>;
	there is no gutter before the first track or after the last track.
	(In particular, there is no <a>gutter</a> between the first/last track of the <a>implicit grid</a>
	and the “auto” lines in the <a>augmented grid</a>.)

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

<h3 id='auto-margins'>
Aligning with <a value for="margin">auto</a> margins</h3>

	Auto [=margins=] on <a>grid items</a> have an effect
	very similar to auto margins in [=block layout=]:

	<ul>
		<li>
			During calculations of <a>grid track</a> sizes,
			''margin/auto'' margins are treated as ''0''.

		<li>
			As defined for the [=inline axis=] of [=block layout=]
			(see <a href="https://www.w3.org/TR/CSS2/visudet.html#blockwidth">CSS2&sect;10.3.3</a>),
			''margin/auto'' margins in either axis absorb positive free space
			prior to alignment via the <a>box alignment properties</a>,
			thereby disabling the effects of any [=self-alignment properties=]
			in that axis.

		<li>
			Overflowing [=grid items=] resolve their ''margin/auto'' margins to zero
			and overflow as specified by their <a>box alignment properties</a>.
	</ul>

<h3 id='row-align'>
Inline-axis Alignment: the 'justify-self' and 'justify-items' properties</h3>

	<a>Grid items</a> can be aligned in the inline dimension
	by using the 'justify-self' property on the <a>grid item</a>
	or 'justify-items' property on the <a>grid container</a>,
	as defined in [[!CSS-ALIGN-3]].

	<div class='example'>
		For example,
		for an English document,
		the inline axis is horizontal,
		and so the 'justify-*' properties align the <a>grid items</a> horizontally.
	</div>

	If <a>baseline alignment</a> is specified on a <a>grid item</a>
	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 <a>fallback alignment</a>
	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.

<h3 id='column-align'>
Block-axis Alignment: the 'align-self' and 'align-items' properties</h3>

	<a>Grid items</a> can also be aligned in the block dimension
	(perpendicular to the inline dimension)
	by using the 'align-self' property on the <a>grid item</a>
	or 'align-items' property on the <a>grid container</a>,
	as defined in [[!CSS-ALIGN-3]].

	If <a>baseline alignment</a> is specified on a <a>grid item</a>
	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 <a>fallback alignment</a>
	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.

<h3 id='grid-align'>
Aligning the Grid: the 'justify-content' and 'align-content' properties</h3>

	If the <a>grid</a>’s outer edges do not correspond to the <a>grid container</a>’s content edges
	(for example, if no columns are flex-sized),
	the <a>grid tracks</a> are aligned within the content box according to the 'justify-content' and 'align-content' properties on the <a>grid container</a>.

	<div class='example'>
		For example, the following grid is centered vertically,
		and aligned to the right edge of its <a>grid container</a>:

		<pre>
			.grid {
				display: grid;
				grid: 12rem 12rem 12rem 12rem / 10rem 10rem 10rem 10rem;
				justify-content: end;
				align-content: center;
				min-height: 60rem;
			}
		</pre>

		<figure>
			<img src="images/align-justify-content.svg" width="352" height="252" alt=''>
		</figure>
	</div>

	If there are no <a>grid tracks</a>
	(the <a>explicit grid</a> is empty, and no tracks were created in the <a>implicit grid</a>),
	the sole <a>grid line</a> in each axis is aligned with the start edge of the <a>grid container</a>.

	Note that certain values of 'justify-content' and 'align-content'
	can cause the tracks to be spaced apart
	(''justify-content/space-around'', ''justify-content/space-between'', ''justify-content/space-evenly'')
	or to be resized (''<content-distribution>/stretch'').
	If the <a>grid</a> is <a>fragmented</a> between tracks,
	any such additional spacing between those tracks must be suppressed.

	<div class="example">
		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:

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

		<figure>
			<img src="images/spanned-gap.svg"
			     alt="Grid with 10px gap and an element spanning all columns.
			          The sum of the columns is less than the width of the grid container." height="426" width="500">
			<figcaption>Grid before alignment</figcaption>
		</figure>
		<figure>
			<img src="images/spanned-gap-align.svg"
			     alt="Same grid with increased gaps absorbing the excess grid container width.
			          The spanning element has grown to accommodate the extra space assigned to the gap it crosses." height="426" width="500">
			<figcaption>Grid after alignment</figcaption>
		</figure>

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

<h3 id='grid-baselines'>
Grid Container Baselines</h3>

	The first [=baseline set=] of a [=grid container=]
	is taken from the first available of:

	1.  If any [=grid items=] intersecting the first ([=block-start=]&ndash;most) non-empty [=track=]
		participate in first [=baseline alignment=] along the relevant axis,
		<a lt="generate baselines">generate</a> a [=baseline set=] from their shared [=alignment baseline=]
		and the [=grid container=]’s [=first available font=],
		after alignment has been performed.

	2.  Otherwise, if any [=grid items=] intersecting that track participate in
		last [=baseline alignment=] along the relevant axis,
		<a lt="generate baselines">generate</a> from <em>that</em> [=alignment baseline=].

	3.  Otherwise, if any [=grid items=] intersecting that track
		have a [=baseline set=] in the relevant axis at all,
		take the [=baseline set=] from the first such [=grid item=] in [=grid order=].

	4. Otherwise, if there are any [=grid items=] at all,
		<a lt="synthesize baselines">synthesize</a> a [=baseline set=]
		from the first [=grid item=] in [=grid order=].

	5. Otherwise, the [=grid container=] has no first <a>baseline set</a> in the relevant axis.
		(One is <a lt="synthesize baselines">synthesized</a>
		from the [=grid container=] itself if needed,
		according to the rules of its <a>alignment context</a>.)

	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 <em>end</em> in the track.

	Last baselines are analogous
	(with “first”/“last” and “start”/“end” inverted).

	<dfn export lt="grid order|grid-modified document order">Grid-modified document order (grid order)</dfn>
	is the order in which <a>grid items</a> are encountered
	when traversing the grid's <a>grid cells</a>.
	If two items are encountered at the same time,
	they are taken in <a>order-modified document order</a>.

	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 <a href="https://www.w3.org/TR/CSS2/tables.html#height-layout">determining the baseline of a table cell</a>,
	a grid container provides a baseline just as a line box or table-row does. [[!CSS2]]

	See [[css-writing-modes-3#intro-baselines]]
	and [[css-align-3#baseline-rules]]
	for more information on baselines.

<!--
 ██████  ████ ████████ ████ ██    ██  ██████
██    ██  ██       ██   ██  ███   ██ ██    ██
██        ██      ██    ██  ████  ██ ██
 ██████   ██     ██     ██  ██ ██ ██ ██   ████
      ██  ██    ██      ██  ██  ████ ██    ██
██    ██  ██   ██       ██  ██   ███ ██    ██
 ██████  ████ ████████ ████ ██    ██  ██████
-->

<h2 id='layout-algorithm' oldids="algo-overview" dfn export>
Grid Layout Algorithm</h2>

	This section defines the <b>grid layout algorithm</b>,
	which sizes the [=grid container=],
	sizes and positions all the [=grid tracks=],
	and lays out the [=grid items=]
	which have been [=grid item placement algorithm|placed=] into its [=grid areas=].

	1. Run the [=Grid Item Placement Algorithm=]
		to resolve the placement of all [=grid items=]
		(including [=subgrids=] and their sub-items)
		in the [=grid=].

	2. Find the size of the [=grid container=],
		per [[#intrinsic-sizes]].

		Note: During this phase,
		cyclic <<percentage>>s in track sizes are treated as ''grid-template-columns/auto''.

	3. Given the resulting [=grid container=] size,
		run the [=Grid Sizing Algorithm=]
		to size the [=grid=].

		Note: During this phase,
		<<percentage>>s in track sizes are resolved
		against the [=grid container=] size.

	4. Lay out the [=grid items=] into their respective containing blocks.
		Each [=grid area's=] width and height
		are considered [=definite=] for this purpose.

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


<h3 id="algo-grid-sizing" dfn export>
Grid Sizing Algorithm</h3>

	This section defines the <b>grid sizing algorithm</b>,
	which determines the size of all <a>grid tracks</a>
	and, by extension, the entire grid.

	Each track has specified <a lt="min track sizing function">minimum</a> and
	<a lt="max track sizing function">maximum</a> <a>sizing functions</a>
	(which may be the same).
	Each <a>sizing function</a> is either:

	<ul>
		<li>A <dfn>fixed sizing function</dfn> (<<length>> or resolvable <<percentage>>).
		<li>An <dfn>intrinsic sizing function</dfn> (''min-content'', ''max-content'', ''grid-template-rows/auto'', ''fit-content()'').
		<li>A <dfn>flexible sizing function</dfn> (<<flex>>).
	</ul>

	The <a>grid sizing algorithm</a> defines how to resolve these sizing constraints into used track sizes.

	<ol>
		<li>
			First, the <a>track sizing algorithm</a> is used to resolve the sizes of the <a>grid columns</a>.

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

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

			If calculating the layout of a <a>grid item</a> in this step
			depends on the <a>available space</a> in the <a>block axis</a>,
			assume the <a>available space</a> that it would have
			if any row with a <a>definite</a> <a>max track sizing function</a>
			had that size and all other rows were infinite.
			If both the <a>grid container</a> and all tracks have <a>definite</a> sizes,
			also apply 'align-content' to find the final effective size
			of any gaps spanned by such items;
			otherwise ignore the effects of track alignment in this estimation.

		<li>
			Next, the <a>track sizing algorithm</a> resolves the sizes of the <a>grid rows</a>.

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

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

			To find the <a>inline-axis</a> <a>available space</a>
			for any items whose <a>block-axis</a> size contributions require it,
			use the <a>grid column</a> sizes calculated in the previous step.
			If the <a>grid container</a>’s <a>inline size</a> is <a>definite</a>,
			also apply 'justify-content'
			to account for the effective column gap sizes.

		<li>
			Then, if the <a>min-content contribution</a> of any grid item has changed
			based on the row sizes and alignment calculated in step 2,
			re-resolve the sizes of the <a>grid columns</a>
			with the new <a lt="min-content contribution">min-content</a>
			and <a>max-content contributions</a> (once only).

			To find the <a>block-axis</a> <a>available space</a>
			for any items whose <a>inline-axis</a> size contributions require it,
			use the <a>grid row</a> sizes calculated in the previous step.
			If the <a>grid container</a>’s <a>block size</a> is <a>definite</a>,
			also apply 'align-content'
			to account for the effective row gap sizes.

			<div class="note">
				This repetition is necessary for cases where the <a>inline size</a> of a <a>grid item</a>
				depends on the <a>block size</a> of its <a>grid area</a>.
				Examples include wrapped column <a>flex containers</a> (''flex-flow: column wrap''),
				<a>orthogonal flows</a> ('writing-mode'),
				<a spec=css-multicol>multi-column containers</a>,
				and items with an aspect-ratio (or with a child with an aspect ratio)
				whose size depends on the size of the row.
			</div>

		<li>
			Next, if the <a>min-content contribution</a> of any grid item has changed
			based on the column sizes and alignment calculated in step 3,
			re-resolve the sizes of the <a>grid rows</a>
			with the new <a lt="min-content contribution">min-content</a>
			and <a>max-content contributions</a> (once only).

			To find the <a>inline-axis</a> <a>available space</a>
			for any items whose <a>block-axis</a> size contributions require it,
			use the <a>grid column</a> sizes calculated in the previous step.
			If the <a>grid container</a>’s <a>inline size</a> is <a>definite</a>,
			also apply 'justify-content'
			to account for the effective column gap sizes.

		<li>
			Finally, align the tracks within the <a>grid container</a>
			according to the 'align-content' and 'justify-content' properties.

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

	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.

	<div class="example">
		The following example illustrates how per-axis subgrids are sized:

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

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

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

		At a high level, the grid algorithm is:

		<ol>
			<li>Size the columns
			<li>Size the rows
			<li>Adjust the columns (if needed based on final row sizes)
		</ol>

		The grid sizing algorithm in this example would thus look like this:
		<ol>
			<li>
				<strong>Resolve sizes of <var>A</var>’s grid columns,
				using the sizes of <var>A</var>’s grid items,
				treating <var>B</var> as empty
				but treating its children
				(including <var>C</var> and <var>D</var>)
				as items in grid <var>A</var>.</strong>

				The grid algorithm simply recurses into <var>D</var>.
				For <var>C</var>, it's more complicated:

				<ol>
					<li>Size <var>C</var>'s columns.
					<li>Size <var>C</var>'s rows by sizing <var>B</var>'s rows.
					<li>Adjust <var>C</var>'s columns.
					<li>Return <var>C</var>'s final column sizes.
				</ol>

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

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

			<li>
				<strong>Next, resolve sizes of <var>A</var>'s rows,
				using the sizes of <var>A</var>’s grid items,
				treating <var>B</var> as a single item.</strong>

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

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

			<li>
				<strong>Last, finalize <var>A</var>’s column sizes.</strong>
				If <var>C</var>’s final size changes
				as a result of the row-sizing pass through <var>B</var>,
				this should trigger a resizing of <var>B</var>’s columns,
				which should trigger a resizing pass on <var>A</var>’s column.
		</ol>
	</div>

<h3 id='algo-terms'>
Track Sizing Terminology</h3>

	<dl noexport>
		<dt><dfn>min track sizing function</dfn>
		<dd>
			If the track was sized with a ''minmax()'' function,
			this is the first argument to that function.
			If the track was sized with a <<flex>> value or ''fit-content()'' function,
			''grid-template-columns/auto''.
			Otherwise, the track's sizing function.

		<dt><dfn>max track sizing function</dfn>
		<dd>
			If the track was sized with a ''minmax()'' function,
			this is the second argument to that function.
			Otherwise, the track's sizing function.
			In all cases, treat ''grid-template-columns/auto'' and ''fit-content()''
			as ''grid-template-columns/max-content'',
			except where specified otherwise for ''fit-content()''.

		<dt><dfn>available grid space</dfn>
		<dd>
			Independently in each dimension, the <a>available grid space</a> is:

			* If the <a>grid container's</a> size is definite,
				then use the size of its content box.
			* If the <a>grid container</a> is being sized under
				a <a>min-content constraint</a> or <a>max-content constraint</a>
				then the <a>available grid space</a> is that constraint
				(and is indefinite).

			Note: ''auto'' sizes that indicate content-based sizing
			(e.g. the height of a block-level box in horizontal writing modes)
			are equivalent to ''max-content''.

			In all cases, clamp the <a>available grid space</a>
			according to the <a>grid container's</a> min/max-width/height properties,
			if they are definite.

		<dt><dfn>free space</dfn>
		<dd>
			Equal to the <a>available grid space</a> minus
			the sum of the <a>base sizes</a> of all the grid tracks (including gutters),
			floored at zero.
			If <a>available grid space</a> is <a>indefinite</a>,
			the <a>free space</a> is <a>indefinite</a> as well.

		<dt><dfn>span count</dfn>
		<dd>
			The number of <a>grid tracks</a> crossed by a <a>grid item</a> in the applicable dimension.
	</dl>

	Note: Remember that [[#gutters|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 <a>track sizing algorithm</a>’s calculations accordingly.

<h3 id="algo-track-sizing">
Track Sizing Algorithm</h3>

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

	<ol>
		<li>[[#algo-init|Initialize Track Sizes]]
		<li>[[#algo-content|Resolve Intrinsic Track Sizes]]
		<li>[[#algo-grow-tracks|Maximize Tracks]]
		<li>[[#algo-flex-tracks|Expand Flexible Tracks]]
		<li><a section href=#algo-stretch>Expand Stretched <css>auto</css> Tracks</a>
	</ol>

<h3 id="algo-init">
Initialize Track Sizes</h3>

	<strong>Initialize each track's base size and growth limit.</strong>
	For each track,
	if the track's <a>min track sizing function</a> is:

	<dl class=switch>
		<dt>A <a>fixed sizing function</a>
		<dd>
			Resolve to an absolute length and use that size as the track’s initial <a>base size</a>.

			Note: <a>Indefinite</a> lengths cannot occur,
			as they're treated as ''auto''.

		<dt>An <a>intrinsic sizing function</a>
		<dd>
			Use an initial <a>base size</a> of zero.
	</dl>

	For each track,
	if the track's <a>max track sizing function</a> is:

	<dl class=switch>
		<dt>A <a>fixed sizing function</a>
		<dd>
			Resolve to an absolute length and use that size as the track’s initial <a>growth limit</a>.

		<dt>An <a>intrinsic sizing function</a>
		<dt>A <a>flexible sizing function</a>
		<dd>
			Use an initial <a>growth limit</a> of infinity.
	</dl>

	In all cases, if the <a>growth limit</a> is less than the <a>base size</a>,
	increase the <a>growth limit</a> to match the <a>base size</a>.

	Note: <a>Gutters</a> are treated as empty fixed-size tracks for the purpose of the <a>track sizing algorithm</a>.

<h3 id="algo-content">
Resolve Intrinsic Track Sizes</h3>

	This step resolves intrinsic track <a>sizing functions</a> 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 <a>base sizes</a> and <a>growth limits</a>
	will have been resolved to absolute lengths.

	Note: [[#algo-terms|Remember that]] ''fit-content()'' and ''auto'' [=max track sizing functions=]
	are treated the same as ''max-content''
	except where explicitly specified otherwise.

<!--
	When the <a>grid container</a> is being sized under a <a>min-content constraint</a>,
	a track with a flexible <a>min track sizing function</a>
	is treated as if its <a>min track sizing function</a> was ''min-content''
	for the purposes of this step.
	<span class='issue'>This seems correct, but should be checked because it wasn't in the original algorithm.</span>
-->

	<ol>
		<li id="algo-baseline-shims">
			<strong>Shim baseline-aligned items
			so their intrinsic size contributions reflect their baseline alignment.</strong>
			For the items in each <a>baseline-sharing group</a>,
			add a “shim” (effectively, additional margin)
			on the start/end side (for first/last-baseline alignment)
			of each item
			so that,
			when start/end-aligned together
			their [[css-align-3#baseline-values|baselines align as specified]].

			Consider these “shims” as part of the items’ intrinsic size contribution
			for the purpose of track sizing, below.
			If an item uses multiple intrinsic size contributions,
			it can have different shims for each one.

			<div class=example>
				For example, when the <a>grid container</a> has an <a>indefinite</a> size,
				it is first laid out under min/max-content constraints to find the size,
				then laid out "for real" with that size
				(which can affect things like percentage tracks).
				The "shims" added for each phase are independent,
				and only affect the layout during that phase.
			</div>

			Note: Note that both [[css-align-3#baseline-align-self|baseline self-aligned]]
			and [[css-align-3#baseline-align-content|baseline content-aligned]] items
			are considered in this step.

			Note: Since <a>grid items</a> whose own size
			depends on the size of an intrinsically-sized track
			[[#row-align|do not participate in baseline alignment]],
			they are not shimmed.

		<li id="algo-single-span-items">
			<strong>Size tracks to fit non-spanning items:</strong>
			For each track with an intrinsic <a>track sizing function</a>
			and not a <a>flexible sizing function</a>,
			consider the items in it with a span of 1:

			<dl class="switch">
				<dt>For min-content minimums:
				<dd>
					If the track has a ''min-content'' <a>min track sizing function</a>,
					set its <a>base size</a>
					to the maximum of the items’ <a>min-content contributions</a>,
					floored at zero.

				<dt>For max-content minimums:
				<dd>
					If the track has a ''max-content'' <a>min track sizing function</a>,
					set its <a>base size</a>
					to the maximum of the items’ <a>max-content contributions</a>,
					floored at zero.

				<dt>For auto minimums:
				<dd>
					If the track has an ''auto'' <a>min track sizing function</a>
					and the <a>grid container</a> is being sized
					under a <a lt="min-content constraint">min-</a>/<a>max-content constraint</a>,
					set the track's <a>base size</a>
					to the maximum of its items’
					<a lt="limited min-content contribution">limited min-content contributions</a>,
					floored at zero.
					The <dfn noexport id="limited-contribution" lt="limited min-content contribution | limited max-content contribution">limited min-/max-content contribution</dfn> of an item
					is (for this purpose) its <a lt="min-content contribution">min-</a>/<a>max-content contribution</a> (accordingly),
					limited by the <a>max track sizing function</a>
					(which could be the argument to a ''fit-content()'' track sizing function)
					if that is <a lt="fixed sizing function">fixed</a>
					<!-- ,
					else by it's own <a>min-content contribution</a>
					if the <a>max track sizing function</a>
					is ''grid-template-columns/min-content'';-->
					and ultimately floored by its <a>minimum contribution</a> (defined below).

					Otherwise,
					set the track's <a>base size</a>
					to the maximum of its items’ <a>minimum contributions</a>,
					floored at zero.
					The <dfn noexport oldids="min-size-contribution">minimum contribution</dfn> of an item
					is the smallest <a>outer size</a> it can have.
					Specifically,
					if the item’s computed <a>preferred size</a> [=behaves as auto=]
					or depends on the size of its <a>containing block</a> in the relevant axis,
					its <a>minimum contribution</a> is
					the <a>outer size</a> that would result from assuming
					the item’s used <a>minimum size</a>
					as its <a>preferred size</a>;
					else the item’s <a>minimum contribution</a> is
					its <a>min-content contribution</a>.
					Because the <a>minimum contribution</a> often depends
					on the size of the item’s content,
					it is considered a type of <a>intrinsic size contribution</a>.

					Note: For items with a specified minimum size of ''min-width/auto'' (the initial value),
					the <a>minimum contribution</a> is usually equivalent to
					the <a>min-content contribution</a>--
					but can differ in some cases, see [[#min-size-auto]].
					Also, <a>minimum contribution</a> &le; <a>min-content contribution</a> &le; <a>max-content contribution</a>.

				<dt>For min-content maximums:
				<dd>
					If the track has a ''min-content'' <a>max track sizing function</a>,
					set its <a>growth limit</a>
					to the maximum of the items’ <a>min-content contributions</a>.

				<dt>For max-content maximums:
				<dd>
					If the track has a ''max-content'' <a>max track sizing function</a>,
					set its <a>growth limit</a>
					to the maximum of the items’ <a>max-content contributions</a>.
					For ''fit-content()'' maximums,
					furthermore clamp this <a>growth limit</a> by the ''fit-content()'' argument.
			</dl>

			In all cases, if a track’s <a>growth limit</a> is now less than its <a>base size</a>,
			increase the <a>growth limit</a> to match the <a>base size</a>.

			Note: This step is a simplification of the steps below for handling spanning items,
			and should yield the same behavior as running those instructions
			on items with a span of 1.

		<li id="algo-spanning-items">
			<strong>Increase sizes to accommodate spanning items crossing content-sized tracks:</strong>
			Next, consider the items with a span of 2
			that do not span a track with a <a>flexible sizing function</a>.
			<!-- auto-min contribution <= min-content contribution <= max-content contribution -->

			<ol>
				<li id="track-size-intrinsic-min">
					<strong>For intrinsic minimums:</strong>
					First [=distribute extra space=]
					to <a>base sizes</a> of tracks with
					an <a lt="intrinsic sizing function">intrinsic</a> <a>min track sizing function</a>,
					to accommodate these items’ <a>minimum contributions</a>.

					If the grid container is being sized under a
					<a lt="min-content constraint">min-</a> or <a>max-content constraint</a>,
					use the items’ <a>limited min-content contributions</a>
					in place of their <a>minimum contributions</a> here.
					(For an item spanning multiple tracks,
					the upper limit used to calculate
					its <a lt="limited min-content contribution">limited min-/max-content contribution</a>
					is the <em>sum</em> of the <a lt="fixed sizing function">fixed</a>
					<a>max track sizing functions</a>
					of any tracks it spans,
					and is applied if it only spans such tracks.)

				<li id="track-size-content-min">
					<strong>For content-based minimums:</strong>
					Next continue to [=distribute extra space=]
					to the [=base sizes=] of tracks with
					a <a>min track sizing function</a> of ''min-content'' or ''max-content'',
					to accommodate these items' <a>min-content contributions</a>.

				<li id="track-size-max-content-min">
					<strong>For max-content minimums:</strong>
					Next, if the grid container is being sized
					under a <a>max-content constraint</a>,
					continue to [=distribute extra space=]
					to the [=base sizes=] of tracks with
					a <a>min track sizing function</a> of
					''grid-template-columns/auto'' or ''max-content'',
					to accommodate these items' <a>limited max-content contributions</a>.

					In all cases,
					continue to [=distribute extra space=]
					to the [=base sizes=] of tracks with
					a <a>min track sizing function</a> of ''max-content'',
					to accommodate these items' <a>max-content contributions</a>.

				<li>
					If at this point any track’s <a>growth limit</a> is now less than its <a>base size</a>,
					increase its <a>growth limit</a> to match its <a>base size</a>.

				<li>
					<strong>For intrinsic maximums:</strong>
					Next [=distribute extra space=]
					to the [=growth limits=] of tracks with
					<a lt="intrinsic sizing function">intrinsic</a> <a>max track sizing function</a>,
					to accommodate these items' <a>min-content contributions</a>.
					Mark any tracks whose <a>growth limit</a> changed
					from infinite to finite in this step
					as <dfn>infinitely growable</dfn> for the next step.

					<details class="note">
						<summary>Why does the <a>infinitely growable</a> flag exist?</summary>

						<a href="http://lists.w3.org/Archives/Public/www-style/2014Mar/0500.html">Peter Salas explains</a>:

						<blockquote cite="http://lists.w3.org/Archives/Public/www-style/2014Mar/0500.html">
							<pre>
								Consider the following case:

								Two "auto" tracks (i.e. ''minmax(min-content, max-content) minmax(min-content, max-content)'').
								Item 1 is in track 1, and has min-content = max-content = 10.
								Item 2 spans tracks 1 and 2, and has min-content = 30, max-content = 100.

								After resolving min-content/max-content for the first item, we have this.

								track 1: base size = 10 growth limit = 10

								track 2: base size = 0 growth limit = infinity

								Then we resolve min-content/max-content for the second item.

								Phase 1 sets the base size of track 2 to 20 so that the two tracks' base sizes sum to 30.
								Phase 2 does nothing because there are no relevant tracks.
								Phase 3 sets the growth limit of track 2 to 20 so that the two tracks' growth limits sum to 30.
								In phase 4, we need to grow the sum of the growth limits by 70 to accommodate item 2.
								Two options are:

								1. Grow each track's growth limit equally,
									and end up with growth limits = [45, 55].
								2. Grow only the second track's growth limit,
									and end up with growth limits = [10, 90].

								By not considering the just-set growth limit as a constraint during space distribution
								(i.e. by treating it as infinity),
								we get the second result,
								which we considered a better result because the first track remains sized exactly to the first item.
							</pre>
						</blockquote>
					</details>

				<li>
					<strong>For max-content maximums:</strong>
					Lastly continue to [=distribute extra space=]
					to the [=growth limits=] of tracks with
					a <a>max track sizing function</a> of ''max-content'',
					to accommodate these items' <a>max-content contributions</a>.
			</ol>

			Repeat incrementally for items with greater spans until all items have been considered.

		<li id="algo-spanning-flex-items">
			<strong>Increase sizes to accommodate spanning items crossing <a>flexible tracks</a>:</strong>
			Next, repeat the previous step
			instead considering (together, rather than grouped by span size)
			all items
			that <em>do</em> span a track with a <a>flexible sizing function</a>
			while
			<ul>
				<li>
					distributing space <em>only</em> to <a>flexible tracks</a>
					(i.e. treating all other tracks as having a <a>fixed sizing function</a>)
				<li>
					if the sum of the <a>flexible sizing functions</a>
					of all <a>flexible tracks</a> spanned by the item
					is greater than or equal to one,
					distributing space to such tracks
					according to the ratios of their <a>flexible sizing functions</a>
					rather than distributing space equally;
					and if the sum is less than one,
					distributing that proportion of space
					according to the ratios of their <a>flexible sizing functions</a>
					and the rest equally
			</ul>

		<li id="algo-finite-growth">
			If any track still has an infinite <a>growth limit</a>
			(because, for example, it had no items placed in it
			or it is a <a>flexible track</a>),
			set its <a>growth limit</a> to its <a>base size</a>.
	</ol>

	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.

<h4 id="extra-space">
Distributing Extra Space Across Spanned Tracks</h4>

	<div algorithm>
		To <dfn noexport>distribute extra space</dfn>,
		perform the following steps,
		with these inputs:

		* whether to affect [=base sizes=] or [=growth limits=] (the |affected size|s).
		* which tracks to affect (the |affected track|s).
		* what intrinsic size contributions are being accommodated (the |size contribution|s)
			of which grid items spanning those tracks (the |item|s).

		<ol>
			<li>
				Maintain separately for each |affected track|
				a |planned increase|,
				initially set to 0.
				(This prevents the size increases from becoming order-dependent.)

			<li>
				[=list/For each=] accommodated |item|,
				considering only tracks the item spans:

				<ol>
					<li>
						<strong>Find the space to distribute:</strong>
						Subtract the |affected size| of every spanned track
						(not just the |affected track|s)
						from the item's |size contribution|,
						flooring it at zero.
						(For infinite <a>growth limits</a>, substitute the track's <a>base size</a>.)
						This remaining size contribution is the |space| to distribute.

						<pre><var>space</var> = max(0, <var>size contribution</var> - ∑<var>track-sizes</var>)</pre>

					<li>
						<strong>Distribute |space| up to limits:</strong>

						Find the |item-incurred increase| for each |affected track| by:
						distributing the |space| equally among these tracks,
						freezing a track’s |item-incurred increase|
						as its |affected size| + |item-incurred increase|
						reaches its |limit|
						(and continuing to grow the unfrozen tracks as needed).

						For [=base sizes=],
						the |limit| is its [=growth limit=],
						  capped by its ''fit-content()'' argument if any.
						For [=growth limits=],
						the |limit| is the [=growth limit=]
						  if the [=growth limit=] is finite
						  and the track is not [=infinitely growable=],
						otherwise its ''fit-content()'' argument
						  if it has a ''fit-content()'' [=track sizing function=],
						and infinity otherwise.

						Note: If the |affected size| was a <a>growth limit</a>
						and the track is not marked [=infinitely growable=],
						then each |item-incurred increase| will be zero.

					<li>
						<strong>Distribute |space| to non-affected tracks:</strong>

						If extra |space| remains at this point,
						and the item spans both |affected tracks| and non-|affected tracks|,
						distribute space as for the previous step,
						but into the non-|affected tracks| instead.

						Note: This distributes any remaining space into tracks
						that have not yet reached their growth limits,
						instead of violating the growth limits of the |affected tracks|.

					<li>
						<strong>Distribute |space| beyond limits:</strong>

						If extra |space| remains at this point,
						unfreeze and continue to distribute |space| to the |item-incurred increase| of…

						<ul>
							<li>
								when <a href=#track-size-intrinsic-min>accommodating minimum contributions</a>
								or <a href=#track-size-content-min>accommodating min-content contributions</a>
								into [=base sizes=]:
								any |affected track| that happens to also have an intrinsic <a>max track sizing function</a>;
								if there are no such tracks, then all |affected track|s.
							<li>
								when <a href=#track-size-max-content-min>accommodating max-content contributions</a>
								into [=base sizes=]:
								any |affected track| that happens to also have a ''max-content'' <a>max track sizing function</a>;
								if there are no such tracks, then all |affected track|s.
							<li>
								when accommodating any contribution
								into [=growth limits=]:
								any |affected track| that has an intrinsic [=max track sizing function=].
						</ul>

						For this purpose,
						the [=max track sizing function=] of a ''fit-content()'' track
						is treated as ''max-content''
						until the track reaches the limit specified as the ''fit-content()'' argument,
						after which its [=max track sizing function=] is treated as being
						a <a>fixed sizing function</a> of that argument
						(which can change which tracks continue to receive space in this step).

						Note: This step prioritizes the distribution of space
						for accommodating |size contribution|s
						beyond the tracks' current growth limits
						based on the types of their [=max track sizing functions=].

					<li>
						For each |affected track|,
						if the track’s |item-incurred increase| is larger than the track’s |planned increase|
						set the track’s |planned increase| to that value.

				</ol>
			<li>
				<strong>Update the tracks' |affected size|s</strong>
				by adding in the |planned increase|,
				so that the next round of space distribution will account for the increase.
				(If the affected size is an infinite <a>growth limit</a>,
				set it to the track's <a>base size</a> plus the |planned increase|.)
		</ol>
	</div>


<h3 id="algo-grow-tracks">
Maximize Tracks</h3>

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

	For the purpose of this step:
	if sizing the <a>grid container</a> under a <a>max-content constraint</a>,
	the <a>free space</a> is infinite;
	if sizing under a <a>min-content constraint</a>,
	the <a>free space</a> is zero.

	If this would cause the grid to be larger than
	the <a>grid container's</a> <a>inner size</a>
	as limited by its <a property lt=max-width>max-width/height</a>,
	then redo this step,
	treating the <a>available grid space</a> as equal to
	the <a>grid container's</a> <a>inner size</a>
	when it's sized to its <a property lt=max-width>max-width/height</a>.

<h3 id="algo-flex-tracks">
Expand Flexible Tracks</h3>

	This step sizes <a>flexible tracks</a>
	using the largest value it can assign to an ''fr''
	without exceeding the <a>available space</a>.

	First, find the grid's used <a>flex fraction</a>:

	<dl>
		<dt>If the <a>free space</a> is zero
			or if sizing the <a>grid container</a> under a <a>min-content constraint</a>:
		<dd>
			The used <a>flex fraction</a> is zero.

		<dt>Otherwise, if the <a>free space</a> is a <a>definite</a> length:
		<dd>
			The used <a>flex fraction</a> is the result of
			[[#algo-find-fr-size|finding the size of an fr]]
			using all of the <a>grid tracks</a>
			and a <a>space to fill</a> of the <a>available grid space</a>.

		<dt>Otherwise, if the <a>free space</a> is an <a>indefinite</a> length:
		<dd>
			The used <a>flex fraction</a> is the maximum of:

			<ul>
				<li>
					For each flexible track,
					if the flexible track's <a>flex factor</a> is greater than one,
					the result of dividing the track's <a>base size</a> by its <a>flex factor</a>;
					otherwise,
					the track's <a>base size</a>.

				<li>
					For each [=grid item=] that crosses a flexible track,
					the result of
					[[#algo-find-fr-size|finding the size of an fr]]
					using all the grid tracks that the item crosses
					and a <a>space to fill</a> of the item's <a>max-content contribution</a>.
			</ul>

			If using this <a>flex fraction</a> would cause the <a>grid</a> to be smaller than the <a>grid container's</a> <a property lt=min-width>min-width/height</a>
			(or larger than the <a>grid container's</a> <a property lt=max-width>max-width/height</a>),
			then redo this step,
			treating the <a>free space</a> as definite
			and the <a>available grid space</a> as equal to
			the <a>grid container's</a> <a>inner size</a>
			when it's sized to its <a property lt=min-width>min-width/height</a>
			(<a property lt=max-width>max-width/height</a>).
	</dl>

	For each <a>flexible track</a>,
	if the product of the used <a>flex fraction</a> and the track's <a>flex factor</a>
	is greater than the track's <a>base size</a>,
	set its <a>base size</a> to that product.


<h4 id="algo-find-fr-size">
Find the Size of an ''fr''</h4>

	This algorithm finds the largest size that an ''fr'' unit can be
	without exceeding the target size.
	It must be called with a set of <a>grid tracks</a>
	and some quantity of <dfn>space to fill</dfn>.

	<ol>
		<li>
			Let <dfn>leftover space</dfn> be the <a>space to fill</a>
			minus the <a>base sizes</a> of the non-flexible <a>grid tracks</a>.

		<li>
			Let <dfn>flex factor sum</dfn> be the sum of
			the <a>flex factors</a> of the <a>flexible tracks</a>.
			If this value is less than 1,
			set it to 1 instead.

		<li>
			Let the <dfn>hypothetical fr size</dfn>
			be the <a>leftover space</a>
			divided by the <a>flex factor sum</a>.

		<li>
			If the product of the <a>hypothetical fr size</a>
			and a <a>flexible track</a>'s <a>flex factor</a>
			is less than the track's base size,
			restart this algorithm
			treating all such tracks as inflexible.

		<li>
			Return the <a>hypothetical fr size</a>.
	</ol>

<h3 id="algo-stretch">
Stretch <css>auto</css> Tracks</h3>

	When the [=content-distribution property=] of the [=grid container=]
	is ''justify-content/normal'' or ''justify-content/stretch'' in this axis,
	this step expands tracks that have
	an ''grid-template-columns/auto'' <a>max track sizing function</a>
	by dividing any remaining positive, <a>definite</a> <a>free space</a>
	equally amongst them.
	If the <a>free space</a> is <a>indefinite</a>,
	but the <a>grid container</a> has a <a>definite</a> <a property lt=min-width>min-width/height</a>,
	use that size to calculate the <a>free space</a> for this step instead.

<!--
████████ ████████     ███     ██████   ██     ██ ████████ ██    ██ ████████ ████ ██    ██  ██████
██       ██     ██   ██ ██   ██    ██  ███   ███ ██       ███   ██    ██     ██  ███   ██ ██    ██
██       ██     ██  ██   ██  ██        ████ ████ ██       ████  ██    ██     ██  ████  ██ ██
██████   ████████  ██     ██ ██   ████ ██ ███ ██ ██████   ██ ██ ██    ██     ██  ██ ██ ██ ██   ████
██       ██   ██   █████████ ██    ██  ██     ██ ██       ██  ████    ██     ██  ██  ████ ██    ██
██       ██    ██  ██     ██ ██    ██  ██     ██ ██       ██   ███    ██     ██  ██   ███ ██    ██
██       ██     ██ ██     ██  ██████   ██     ██ ████████ ██    ██    ██    ████ ██    ██  ██████
-->

<h2 id='pagination'>
Fragmenting Grid Layout</h2>


	<p>
		<a>Grid containers</a> can break across pages
		between rows or columns
		and inside items.
		The <a property lt="break-before">break-*</a> 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.

	<p>
		The following breaking rules refer to the <a>fragmentation container</a> as the “page”.
		The same rules apply in any other <a>fragmentation context</a>.
		(Substitute “page” with the appropriate <a>fragmentation container</a> type as needed.)
		See the <a href="http://www.w3.org/TR/css-break/">CSS Fragmentation Module</a> [[!CSS3-BREAK]].

	<p>
		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:

	<ul>
		<li>
			The 'break-before' and 'break-after' properties on <a>grid items</a>
			are propagated to their grid row.
			The 'break-before' property on the first row
			and the 'break-after' property on the last row
			are propagated to the grid container.

		<li>
			A forced break inside a grid item effectively increases the size of its contents;
			it does not trigger a forced break inside sibling items.

		<li>
			<a href="https://www.w3.org/TR/css3-break/#btw-blocks">Class A break opportunities</a> occur
			between rows or columns (whichever is in the appropriate axis),
			and <a href="https://www.w3.org/TR/css3-break/#end-block">Class C break opportunities</a> occur
			between the first/last row (column) and the grid container's content edges.
			[[!CSS3-BREAK]]

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

		<li>
			Aside from the rearrangement of items imposed by the previous point,
			UAs should attempt to minimize distortion of the grid container
			with respect to unfragmented flow.
	</ul>


<h3 id="fragmentation-alg">
Sample Fragmentation Algorithm</h3>

	<p><em>This section is non-normative.</em>

	<p class="note">
		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.

	<ol>
		<li>
			Layout the grid following the [[#layout-algorithm]] by using the
			<a>fragmentation container</a>’s inline size and assume unlimited block size.
			During this step all 'grid-row' ''auto'' and ''fr'' values must be resolved.

		<li>
			Layout the grid container using the values resolved in the previous step.

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

			<ul>
				<li>
					have a content min track sizing function.

				<li>
					are in a grid that does not have an explicit height and the grid row is flexible.
			</ul>

		<li>
			If the grid height is ''auto'', the height of the grid should be the sum of the final
			row sizes.

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

	<p class="note">
		If the grid’s height is specified, steps three and four may cause the grid rows to
		overflow the grid.
	</p>

Privacy Considerations {#privacy}
===============================================

	Grid Layout introduces no new privacy leaks.

Security Considerations {#security}
=================================

	Grid Layout introduces no new security considerations.

<h2 id="changes">
Changes</h2>

<h3 id="changes-202012">
Changes since the <a href="https://www.w3.org/TR/2020/CRD-css-grid-2-20201218/">18 December 2020 CR</a></h3>

	<ul class="non-normative">
		<li>
			Clarified how [=relative positioning=] applies to [=subgrids=].
			(<a href="https://github.com/w3c/csswg-drafts/issues/7123">Issue 7123</a>)
			<blockquote>
				<ul>
					<li>
						<ins>[=Relative positioning=] applies to <a>subgrids</a> as normal,
						and shifts the box and its content together as usual.
						(Note: Relative positioning takes place after alignment,
						and does not affect track sizing.)</ins>
				</ul>
			</blockquote>
		<li>
			Clarified that the [=scrollbar gutter=] is accounted for alongside the margin/border/padding
			when calculating the contribution of the subgrid itself
			(not just when accounting for its children).
			(<a href="https://github.com/w3c/csswg-drafts/issues/9935">Issue 9935</a>)
			<blockquote>
				<p>For each edge of a non-empty [=subgrid=],
				to account for the subgrid’s margin/border/padding <ins>(and any scrollbar gutter)</ins> at that edge,
				&hellip;
				and are additionally inflated by the subgrid’s own margin/border/padding<ins>/gutter</ins>
				at that edge.
			</blockquote>
		<li>
			Also incorporated <a href="https://www.w3.org/TR/2025/CRD-css-grid-1-20250326/#changes-202012">all changes to CSS Grid Level 1 since its previous publication</a>.
	</ul>

<h3 id="changes-202008">
Changes since the <a href="https://www.w3.org/TR/2020/CR-css-grid-2-20200818/">August 2020 CR</a></h3>

	<ul class="non-normative">
		<li id="change-2020-align-normal-aspect-ratio">
			Fix errors introduced by in the previous CR of CSS Grid 1 by an undocumented attempt to clarify [[#grid-item-sizing]] interaction with 'aspect-ratio'.
		<li id="change-2020-preferred-aspect-ratio">
			Updated some instances of “intrinsic aspect ratio”
			to use the more generic term [=preferred aspect ratio=].
			(<a href="https://github.com/w3c/csswg-drafts/issues/4962">Issue 4962</a>)
		<li id="change-2020-editorial">
			Minor editorial clean-up and better alignment of terminology across specs.
	</ul>

<h3 class="no-num" id="changes-20180904">
Changes since the
<a href="https://www.w3.org/TR/2019/WD-css-grid-2-20191203/">December 2019 CSS Grid Layout Level 2 Working Draft</a></h3>

	<p>None, except the incorporation of the full text of <a href="https://www.w3.org/TR/css-grid-1/">CSS Grid level 1</a>.

	See <a href="https://www.w3.org/TR/2019/WD-css-grid-2-20191203/#changes">Changes during Working Draft</a>
	for previous changes.

<h3 id="changes-2">
Additions Since Level 1</h3>

	The following features have been added since
	<a href="http://www.w3.org/TR/css-grid-1/">Level 1</a>:

	<ul>
		<li>[[#subgrids|Subgrids]] (''subgrid'')
	</ul>

<h2 id="acknowledgements">
Acknowledgements</h2>

	Many thanks to Mats Palmgren of Mozilla,
	without whose support and feedback the subgrid feature
	would not be able to move forward.
	Thanks also to Daniel Tonon,
	who insisted on intelligent handling of gaps in subgrids
	and contributed illustrations;
<!-- add this in once we spec it
	to Eric Meyer,
	who asked us to define useful behavior for <<flex>> min track sizes;
-->
	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
	<a href="https://www.w3.org/TR/css-grid-1/">CSS Grid Level 1</a> possible.
