CSS Grid Layout is the most powerful layout system available in CSS. It is a 2-dimensional system, meaning it can handle both columns and rows, unlike flexbox which is largely a 1-dimensional system. You work with Grid Layout by applying CSS rules both to a parent element (which becomes the Grid Container) and to that element’s children (which become Grid Items).
Introduction
CSS Grid Layout (aka “Grid”), is a two-dimensional grid-based layout system that aims to do nothing less than completely change the way we design grid-based user interfaces. CSS has always been used to lay out our web pages, but it’s never done a very good job of it. First, we used tables, then floats, positioning and inline-block, but all of these methods were essentially hacks and left out a lot of important functionality (vertical centering, for instance). Flexbox helped out, but it’s intended for simpler one-dimensional layouts, not complex two-dimensional ones (Flexbox and Grid actually work very well together). Grid is the very first CSS module created specifically to solve the layout problems we’ve all been hacking our way around for as long as we’ve been making websites.
There are two primary things that inspired me to create this guide. The first is Rachel Andrew’s awesome book Get Ready for CSS Grid Layout. It’s a thorough, clear introduction to Grid and is the basis of this entire article. I highly encourage you to buy it and read it. My other big inspiration is Chris Coyier’s A Complete Guide to Flexbox, which has been my go-to resource for everything flexbox. It’s helped a ton of people, evident by the fact that it’s the top result when you Google “flexbox.” You’ll notice many similarities between his post and mine, because why not steal from the best?
My intention with this guide is to present the Grid concepts as they exist in the very latest version of the specification. So I won’t be covering the out of date IE syntax, and I’ll do my best to update this guide regularly as the spec matures.
Basics and Browser Support
As of March 2017, most browsers shipped native, unprefixed support for CSS Grid: Chrome (including on Android), Firefox, Safari (including on iOS), and Opera. Internet Explorer 10 and 11 on the other hand support it, but it’s an old implementation with an outdated syntax. The time to build with grid is now!
To get started you have to define a container element as a grid with display: grid
, set the column and row sizes with grid-template-columns
and grid-template-rows
, and then place its child elements into the grid with grid-column
and grid-row
. Similarly to flexbox, the source order of the grid items doesn’t matter. Your CSS can place them in any order, which makes it super easy to rearrange your grid with media queries. Imagine defining the layout of your entire page, and then completely rearranging it to accommodate a different screen width all with only a couple lines of CSS. Grid is one of the most powerful CSS modules ever introduced.
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Desktop
Chrome | Firefox | IE | Edge | Safari |
---|---|---|---|---|
57 | 52 | 11* | 16 | 10.1 |
Mobile / Tablet
Android Chrome | Android Firefox | Android | iOS Safari |
---|---|---|---|
87 | 83 | 81 | 10.3 |
Important Terminology
Before diving into the concepts of Grid it’s important to understand the terminology. Since the terms involved here are all kinda conceptually similar, it’s easy to confuse them with one another if you don’t first memorize their meanings defined by the Grid specification. But don’t worry, there aren’t many of them.
Grid Container
The element on which display: grid
is applied. It’s the direct parent of all the grid items. In this example container
is the grid container.
<div class="container">
<div class="item item-1"> </div>
<div class="item item-2"> </div>
<div class="item item-3"> </div>
</div>
Grid Line
The dividing lines that make up the structure of the grid. They can be either vertical (“column grid lines”) or horizontal (“row grid lines”) and reside on either side of a row or column. Here the yellow line is an example of a column grid line.
Grid Track
The space between two adjacent grid lines. You can think of them like the columns or rows of the grid. Here’s the grid track between the second and third row grid lines.
Grid Area
The total space surrounded by four grid lines. A grid area may be composed of any number of grid cells. Here’s the grid area between row grid lines 1 and 3, and column grid lines 1 and 3.
Grid Item
The children (i.e. direct descendants) of the grid container. Here the item
elements are grid items, but sub-item
isn’t.
<div class="container">
<div class="item"> </div>
<div class="item">
<p class="sub-item"> </p>
</div>
<div class="item"> </div>
</div>
Grid Cell
The space between two adjacent row and two adjacent column grid lines. It’s a single “unit” of the grid. Here’s the grid cell between row grid lines 1 and 2, and column grid lines 2 and 3.
The Most Powerful Lines in Grid
Fluid width columns that break into more or less columns as space is available, with no media queries!
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
/* This is better for small screens, once min() is better supported */
/* grid-template-columns: repeat(auto-fill, minmax(min(200px, 100%), 1fr)); */
grid-gap: 1rem;
/* This is the standardized property now, but has slightly less support */
/* gap: 1rem */
}
Grid Properties Table of Contents
Properties for the Grid Container
Properties for the Grid Items
Properties for the Parent
(Grid Container)
display
Defines the element as a grid container and establishes a new grid formatting context for its contents.
Values:
- grid – generates a block-level grid
- inline-grid – generates an inline-level grid
.container {
display: grid | inline-grid;
}
Note: The ability to pass grid parameters down through nested elements (aka subgrids) has been moved to level 2 of the CSS Grid specification. Here’s a quick explanation.
grid-template-columns
grid-template-rows
Defines the columns and rows of the grid with a space-separated list of values. The values represent the track size, and the space between them represents the grid line.
Values:
- <track-size> – can be a length, a percentage, or a fraction of the free space in the grid (using the
fr
unit) - <line-name> – an arbitrary name of your choosing
.container {
grid-template-columns: ... | ...;
grid-template-rows: ... | ...;
}
Examples:
When you leave an empty space between the track values, the grid lines are automatically assigned positive and negative numbers:
.container {
grid-template-columns: 40px 50px auto 50px 40px;
grid-template-rows: 25% 100px auto;
}
But you can choose to explicitly name the lines. Note the bracket syntax for the line names:
.container {
grid-template-columns: [first] 40px [line2] 50px [line3] auto [col4-start] 50px [five] 40px [end];
grid-template-rows: [row1-start] 25% [row1-end] 100px [third-line] auto [last-line];
}
Note that a line can have more than one name. For example, here the second line will have two names: row1-end and row2-start:
.container {
grid-template-rows: [row1-start] 25% [row1-end row2-start] 25% [row2-end];
}
If your definition contains repeating parts, you can use the repeat()
notation to streamline things:
.container {
grid-template-columns: repeat(3, 20px [col-start]);
}
Which is equivalent to this:
.container {
grid-template-columns: 20px [col-start] 20px [col-start] 20px [col-start];
}
If multiple lines share the same name, they can be referenced by their line name and count.
.item {
grid-column-start: col-start 2;
}
The fr
unit allows you to set the size of a track as a fraction of the free space of the grid container. For example, this will set each item to one third the width of the grid container:
.container {
grid-template-columns: 1fr 1fr 1fr;
}
The free space is calculated after any non-flexible items. In this example the total amount of free space available to the fr
units doesn’t include the 50px:
.container {
grid-template-columns: 1fr 50px 1fr 1fr;
}
grid-template-areas
Defines a grid template by referencing the names of the grid areas which are specified with the grid-area
property. Repeating the name of a grid area causes the content to span those cells. A period signifies an empty cell. The syntax itself provides a visualization of the structure of the grid.
Values:
- <grid-area-name> – the name of a grid area specified with
grid-area
- . – a period signifies an empty grid cell
- none – no grid areas are defined
.container {
grid-template-areas:
" | . | none | ..."
"...";
}
Example:
.item-a {
grid-area: header;
}
.item-b {
grid-area: main;
}
.item-c {
grid-area: sidebar;
}
.item-d {
grid-area: footer;
}
.container {
display: grid;
grid-template-columns: 50px 50px 50px 50px;
grid-template-rows: auto;
grid-template-areas:
"header header header header"
"main main . sidebar"
"footer footer footer footer";
}
That’ll create a grid that’s four columns wide by three rows tall. The entire top row will be composed of the header area. The middle row will be composed of two main areas, one empty cell, and one sidebar area. The last row is all footer.
Each row in your declaration needs to have the same number of cells.
You can use any number of adjacent periods to declare a single empty cell. As long as the periods have no spaces between them they represent a single cell.
Notice that you’re not naming lines with this syntax, just areas. When you use this syntax the lines on either end of the areas are actually getting named automatically. If the name of your grid area is foo, the name of the area’s starting row line and starting column line will be foo-start, and the name of its last row line and last column line will be foo-end. This means that some lines might have multiple names, such as the far left line in the above example, which will have three names: header-start, main-start, and footer-start.
grid-template
A shorthand for setting grid-template-rows
, grid-template-columns
, and grid-template-areas
in a single declaration.
Values:
- none – sets all three properties to their initial values
- <grid-template-rows> / <grid-template-columns> – sets
grid-template-columns
andgrid-template-rows
to the specified values, respectively, and setsgrid-template-areas
tonone
.container {
grid-template: none | <grid-template-rows> / <grid-template-columns>;
}
It also accepts a more complex but quite handy syntax for specifying all three. Here’s an example:
.container {
grid-template:
[row1-start] "header header header" 25px [row1-end]
[row2-start] "footer footer footer" 25px [row2-end]
/ auto 50px auto;
}
That’s equivalent to this:
.container {
grid-template-rows: [row1-start] 25px [row1-end row2-start] 25px [row2-end];
grid-template-columns: auto 50px auto;
grid-template-areas:
"header header header"
"footer footer footer";
}
Since grid-template
doesn’t reset the implicit grid properties (grid-auto-columns
, grid-auto-rows
, and grid-auto-flow
), which is probably what you want to do in most cases, it’s recommended to use the grid
property instead of grid-template
.
column-gap
row-gap
grid-column-gap
grid-row-gap
Specifies the size of the grid lines. You can think of it like setting the width of the gutters between the columns/rows.
Values:
- <line-size> – a length value
.container {
/* standard */
column-gap: <line-size>;
row-gap: <line-size>;
/* old */
grid-column-gap: <line-size>;
grid-row-gap: <line-size>;
}
Example:
.container {
grid-template-columns: 100px 50px 100px;
grid-template-rows: 80px auto 80px;
column-gap: 10px;
row-gap: 15px;
}
The gutters are only created between the columns/rows, not on the outer edges.
Note: The grid-
prefix will be removed and grid-column-gap
and grid-row-gap
renamed to column-gap
and row-gap
. The unprefixed properties are already supported in Chrome 68+, Safari 11.2 Release 50+ and Opera 54+.
gap
grid-gap
A shorthand for row-gap
and column-gap
Values:
- <grid-row-gap> <grid-column-gap> – length values
.container {
/* standard */
gap: <grid-row-gap> <grid-column-gap>;
/* old */
grid-gap: <grid-row-gap> <grid-column-gap>;
}
Example:
.container {
grid-template-columns: 100px 50px 100px;
grid-template-rows: 80px auto 80px;
gap: 15px 10px;
}
If no row-gap
is specified, it’s set to the same value as column-gap
Note: The grid-
prefix is deprecated (but who knows, may never actually be removed from browsers). Essentially grid-gap
renamed to gap
. The unprefixed property is already supported in Chrome 68+, Safari 11.2 Release 50+, and Opera 54+.
justify-items
Aligns grid items along the inline (row) axis (as opposed to align-items
which aligns along the block (column) axis). This value applies to all grid items inside the container.
Values:
- start – aligns items to be flush with the start edge of their cell
- end – aligns items to be flush with the end edge of their cell
- center – aligns items in the center of their cell
- stretch – fills the whole width of the cell (this is the default)
.container {
justify-items: start | end | center | stretch;
}
Examples:
.container {
justify-items: start;
}
.container {
justify-items: end;
}
.container {
justify-items: center;
}
.container {
justify-items: stretch;
}
This behavior can also be set on individual grid items via the justify-self
property.
align-items
Aligns grid items along the block (column) axis (as opposed to justify-items
which aligns along the inline (row) axis). This value applies to all grid items inside the container.
Values:
- start – aligns items to be flush with the start edge of their cell
- end – aligns items to be flush with the end edge of their cell
- center – aligns items in the center of their cell
- stretch – fills the whole height of the cell (this is the default)
.container {
align-items: start | end | center | stretch;
}
Examples:
.container {
align-items: start;
}
.container {
align-items: end;
}
.container {
align-items: center;
}
.container {
align-items: stretch;
}
This behavior can also be set on individual grid items via the align-self
property.
place-items
place-items
sets both the align-items
and justify-items
properties in a single declaration.
Values:
- <align-items> / <justify-items> – The first value sets
align-items
, the second valuejustify-items
. If the second value is omitted, the first value is assigned to both properties.
All major browsers except Edge support the place-items
shorthand property.
For more details, see align-items and justify-items.
justify-content
Sometimes the total size of your grid might be less than the size of its grid container. This could happen if all of your grid items are sized with non-flexible units like px
. In this case you can set the alignment of the grid within the grid container. This property aligns the grid along the inline (row) axis (as opposed to align-content
which aligns the grid along the block (column) axis).
Values:
- start – aligns the grid to be flush with the start edge of the grid container
- end – aligns the grid to be flush with the end edge of the grid container
- center – aligns the grid in the center of the grid container
- stretch – resizes the grid items to allow the grid to fill the full width of the grid container
- space-around – places an even amount of space between each grid item, with half-sized spaces on the far ends
- space-between – places an even amount of space between each grid item, with no space at the far ends
- space-evenly – places an even amount of space between each grid item, including the far ends
.container {
justify-content: start | end | center | stretch | space-around | space-between | space-evenly;
}
Examples:
.container {
justify-content: start;
}
.container {
justify-content: end;
}
.container {
justify-content: center;
}
.container {
justify-content: stretch;
}
.container {
justify-content: space-around;
}
.container {
justify-content: space-between;
}
.container {
justify-content: space-evenly;
}
align-content
Sometimes the total size of your grid might be less than the size of its grid container. This could happen if all of your grid items are sized with non-flexible units like px
. In this case you can set the alignment of the grid within the grid container. This property aligns the grid along the block (column) axis (as opposed to justify-content
which aligns the grid along the inline (row) axis).
Values:
- start – aligns the grid to be flush with the start edge of the grid container
- end – aligns the grid to be flush with the end edge of the grid container
- center – aligns the grid in the center of the grid container
- stretch – resizes the grid items to allow the grid to fill the full height of the grid container
- space-around – places an even amount of space between each grid item, with half-sized spaces on the far ends
- space-between – places an even amount of space between each grid item, with no space at the far ends
- space-evenly – places an even amount of space between each grid item, including the far ends
.container {
align-content: start | end | center | stretch | space-around | space-between | space-evenly;
}
Examples:
.container {
align-content: start;
}
.container {
align-content: end;
}
.container {
align-content: center;
}
.container {
align-content: stretch;
}
.container {
align-content: space-around;
}
.container {
align-content: space-between;
}
.container {
align-content: space-evenly;
}
place-content
place-content
sets both the align-content
and justify-content
properties in a single declaration.
Values:
- <align-content> / <justify-content> – The first value sets
align-content
, the second valuejustify-content
. If the second value is omitted, the first value is assigned to both properties.
All major browsers except Edge support the place-content
shorthand property.
For more details, see align-content and justify-content.
grid-auto-columns
grid-auto-rows
Specifies the size of any auto-generated grid tracks (aka implicit grid tracks). Implicit tracks get created when there are more grid items than cells in the grid or when a grid item is placed outside of the explicit grid. (see The Difference Between Explicit and Implicit Grids)
Values:
- <track-size> – can be a length, a percentage, or a fraction of the free space in the grid (using the
fr
unit)
.container {
grid-auto-columns: <track-size> ...;
grid-auto-rows: <track-size> ...;
}
To illustrate how implicit grid tracks get created, think about this:
.container {
grid-template-columns: 60px 60px;
grid-template-rows: 90px 90px;
}
This creates a 2 x 2 grid.
But now imagine you use grid-column
and grid-row
to position your grid items like this:
.item-a {
grid-column: 1 / 2;
grid-row: 2 / 3;
}
.item-b {
grid-column: 5 / 6;
grid-row: 2 / 3;
}
We told .item-b to start on column line 5 and end at column line 6, but we never defined a column line 5 or 6. Because we referenced lines that don’t exist, implicit tracks with widths of 0 are created to fill in the gaps. We can use grid-auto-columns
and grid-auto-rows
to specify the widths of these implicit tracks:
.container {
grid-auto-columns: 60px;
}
grid-auto-flow
If you have grid items that you don’t explicitly place on the grid, the auto-placement algorithm kicks in to automatically place the items. This property controls how the auto-placement algorithm works.
Values:
- row – tells the auto-placement algorithm to fill in each row in turn, adding new rows as necessary (default)
- column – tells the auto-placement algorithm to fill in each column in turn, adding new columns as necessary
- dense – tells the auto-placement algorithm to attempt to fill in holes earlier in the grid if smaller items come up later
.container {
grid-auto-flow: row | column | row dense | column dense;
}
Note that dense only changes the visual order of your items and might cause them to appear out of order, which is bad for accessibility.
Examples:
Consider this HTML:
<section class="container">
<div class="item-a">item-a</div>
<div class="item-b">item-b</div>
<div class="item-c">item-c</div>
<div class="item-d">item-d</div>
<div class="item-e">item-e</div>
</section>
You define a grid with five columns and two rows, and set grid-auto-flow
to row
(which is also the default):
.container {
display: grid;
grid-template-columns: 60px 60px 60px 60px 60px;
grid-template-rows: 30px 30px;
grid-auto-flow: row;
}
When placing the items on the grid, you only specify spots for two of them:
.item-a {
grid-column: 1;
grid-row: 1 / 3;
}
.item-e {
grid-column: 5;
grid-row: 1 / 3;
}
Because we set grid-auto-flow
to row
, our grid will look like this. Notice how the three items we didn’t place (item-b, item-c and item-d) flow across the available rows:
If we instead set grid-auto-flow
to column
, item-b, item-c and item-d flow down the columns:
.container {
display: grid;
grid-template-columns: 60px 60px 60px 60px 60px;
grid-template-rows: 30px 30px;
grid-auto-flow: column;
}
grid
A shorthand for setting all of the following properties in a single declaration: grid-template-rows
, grid-template-columns
, grid-template-areas
, grid-auto-rows
, grid-auto-columns
, and grid-auto-flow
(Note: You can only specify the explicit or the implicit grid properties in a single grid declaration).
Values:
- none – sets all sub-properties to their initial values.
- <grid-template> – works the same as the
grid-template
shorthand. - <grid-template-rows> / [ auto-flow && dense? ] <grid-auto-columns>? – sets
grid-template-rows
to the specified value. If theauto-flow
keyword is to the right of the slash, it setsgrid-auto-flow
tocolumn
. If thedense
keyword is specified additionally, the auto-placement algorithm uses a “dense” packing algorithm. Ifgrid-auto-columns
is omitted, it is set toauto
. - [ auto-flow && dense? ] <grid-auto-rows>? / <grid-template-columns> – sets
grid-template-columns
to the specified value. If theauto-flow
keyword is to the left of the slash, it setsgrid-auto-flow
torow
. If thedense
keyword is specified additionally, the auto-placement algorithm uses a “dense” packing algorithm. Ifgrid-auto-rows
is omitted, it is set toauto
.
Examples:
The following two code blocks are equivalent:
.container {
grid: 100px 300px / 3fr 1fr;
}
.container {
grid-template-rows: 100px 300px;
grid-template-columns: 3fr 1fr;
}
The following two code blocks are equivalent:
.container {
grid: auto-flow / 200px 1fr;
}
.container {
grid-auto-flow: row;
grid-template-columns: 200px 1fr;
}
The following two code blocks are equivalent:
.container {
grid: auto-flow dense 100px / 1fr 2fr;
}
.container {
grid-auto-flow: row dense;
grid-auto-rows: 100px;
grid-template-columns: 1fr 2fr;
}
And the following two code blocks are equivalent:
.container {
grid: 100px 300px / auto-flow 200px;
}
.container {
grid-template-rows: 100px 300px;
grid-auto-flow: column;
grid-auto-columns: 200px;
}
It also accepts a more complex but quite handy syntax for setting everything at once. You specify grid-template-areas
, grid-template-rows
and grid-template-columns
, and all the other sub-properties are set to their initial values. What you’re doing is specifying the line names and track sizes inline with their respective grid areas. This is easiest to describe with an example:
.container {
grid: [row1-start] "header header header" 1fr [row1-end]
[row2-start] "footer footer footer" 25px [row2-end]
/ auto 50px auto;
}
That’s equivalent to this:
.container {
grid-template-areas:
"header header header"
"footer footer footer";
grid-template-rows: [row1-start] 1fr [row1-end row2-start] 25px [row2-end];
grid-template-columns: auto 50px auto;
}
Properties for the Children
(Grid Items)
Note:float
, display: inline-block
, display: table-cell
, vertical-align
and column-*
properties have no effect on a grid item.
grid-column-start
grid-column-end
grid-row-start
grid-row-end
Determines a grid item’s location within the grid by referring to specific grid lines. grid-column-start
/grid-row-start
is the line where the item begins, and grid-column-end
/grid-row-end
is the line where the item ends.
Values:
- <line> – can be a number to refer to a numbered grid line, or a name to refer to a named grid line
- span <number> – the item will span across the provided number of grid tracks
- span <name> – the item will span across until it hits the next line with the provided name
- auto – indicates auto-placement, an automatic span, or a default span of one
.item {
grid-column-start: <number> | <name> | span <number> | span <name> | auto;
grid-column-end: <number> | <name> | span <number> | span <name> | auto;
grid-row-start: <number> | <name> | span <number> | span <name> | auto;
grid-row-end: <number> | <name> | span <number> | span <name> | auto;
}
Examples:
.item-a {
grid-column-start: 2;
grid-column-end: five;
grid-row-start: row1-start;
grid-row-end: 3;
}
.item-b {
grid-column-start: 1;
grid-column-end: span col4-start;
grid-row-start: 2;
grid-row-end: span 2;
}
If no grid-column-end
/grid-row-end
is declared, the item will span 1 track by default.
Items can overlap each other. You can use z-index
to control their stacking order.
grid-column
grid-row
Shorthand for grid-column-start
+ grid-column-end
, and grid-row-start
+ grid-row-end
, respectively.
Values:
- <start-line> / <end-line> – each one accepts all the same values as the longhand version, including span
.item {
grid-column: <start-line> / <end-line> | <start-line> / span <value>;
grid-row: <start-line> / <end-line> | <start-line> / span <value>;
}
Example:
.item-c {
grid-column: 3 / span 2;
grid-row: third-line / 4;
}
If no end line value is declared, the item will span 1 track by default.
grid-area
Gives an item a name so that it can be referenced by a template created with the grid-template-areas
property. Alternatively, this property can be used as an even shorter shorthand for grid-row-start
+ grid-column-start
+ grid-row-end
+ grid-column-end
.
Values:
- <name> – a name of your choosing
- <row-start> / <column-start> / <row-end> / <column-end> – can be numbers or named lines
.item {
grid-area: <name> | <row-start> / <column-start> / <row-end> / <column-end>;
}
Examples:
As a way to assign a name to the item:
.item-d {
grid-area: header;
}
As the short-shorthand for grid-row-start
+ grid-column-start
+ grid-row-end
+ grid-column-end
:
.item-d {
grid-area: 1 / col4-start / last-line / 6;
}
justify-self
Aligns a grid item inside a cell along the inline (row) axis (as opposed to align-self
which aligns along the block (column) axis). This value applies to a grid item inside a single cell.
Values:
- start – aligns the grid item to be flush with the start edge of the cell
- end – aligns the grid item to be flush with the end edge of the cell
- center – aligns the grid item in the center of the cell
- stretch – fills the whole width of the cell (this is the default)
.item {
justify-self: start | end | center | stretch;
}
Examples:
.item-a {
justify-self: start;
}
.item-a {
justify-self: end;
}
.item-a {
justify-self: center;
}
.item-a {
justify-self: stretch;
}
To set alignment for all the items in a grid, this behavior can also be set on the grid container via the justify-items
property.
align-self
Aligns a grid item inside a cell along the block (column) axis (as opposed to justify-self
which aligns along the inline (row) axis). This value applies to the content inside a single grid item.
Values:
- start – aligns the grid item to be flush with the start edge of the cell
- end – aligns the grid item to be flush with the end edge of the cell
- center – aligns the grid item in the center of the cell
- stretch – fills the whole height of the cell (this is the default)
.item {
align-self: start | end | center | stretch;
}
Examples:
.item-a {
align-self: start;
}
.item-a {
align-self: end;
}
.item-a {
align-self: center;
}
.item-a {
align-self: stretch;
}
To align all the items in a grid, this behavior can also be set on the grid container via the align-items
property.
place-self
place-self
sets both the align-self
and justify-self
properties in a single declaration.
Values:
- auto – The “default” alignment for the layout mode.
- <align-self> / <justify-self> – The first value sets
align-self
, the second valuejustify-self
. If the second value is omitted, the first value is assigned to both properties.
Examples:
.item-a {
place-self: center;
}
.item-a {
place-self: center stretch;
}
All major browsers except Edge support the place-self
shorthand property.
Special Functions and Keywords
- When sizing rows and columns, you can use all the lengths you are used to, like
px
, rem, %, etc, but you also have keywords likemin-content
,max-content
,auto
, and perhaps the most useful, fractional units.grid-template-columns: 200px 1fr 2fr min-content;
- You also have access to a function which can help set boundaries for otherwise flexible units. For example to set a column to be 1fr, but shrink no further than 200px:
grid-template-columns: 1fr minmax(200px, 1fr);
- There is
repeat()
function, which saves some typing, like making 10 columns:grid-template-columns: repeat(10, 1fr);
- Combining all of these things can be extremely powerful, like
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
See the demo at the top of the page about “The Most Powerful Lines in Grid”.
Animation
According to the CSS Grid Layout Module Level 1 specification, there are 5 animatable grid properties:
grid-gap
,grid-row-gap
,grid-column-gap
as length, percentage, or calc.grid-template-columns
,grid-template-rows
as a simple list of length, percentage, or calc, provided the only differences are the values of the length, percentage, or calc components in the list.
Browser Support of CSS Grid properties
As of today (May 7th, 2018) only the animation of (grid-)gap
, (grid-)row-gap
, (grid-)column-gap
is implemented in any of the tested browsers.
Browser | (grid-)gap , (grid-)row-gap , (grid-)column-gap | grid-template-columns | grid-template-rows |
---|---|---|---|
Firefox | supported ✅ 53+ | supported ✅ 66+ | supported ✅ 66+ |
Safari 12.0 | not supported ❌ | not supported ❌ | not supported ❌ |
Chrome | supported ✅ 66+ | not supported ❌ | not supported ❌ |
Chrome for Android 66+, Opera Mini 33+ | supported ✅ | not supported ❌ | not supported ❌ |
Edge | supported ✅ 16+ | not supported ❌ | not supported ❌ |
Awesome article! thanks for the early peek at the grid spec.
Maybe it was just how you did your examples but one thing I didnt like was how the margin was also a row/column. I felt it took away from the clarity of the grid semantics, as you have to remember to put something in row 3 rather than 2 because 2 is supposed to be a margin. It feels just as weird as the ole spacer divs from way back in the day.
Is there any properties like grid-spacing or grid-row-margin/grid-column-margin? These would feel much more natural.
example:
say we have 4 rows in our grid layout (same concept would apply for columns)
thoughts?
Currently you can only do it like in the article adding the gutters directly as any other row/column.
However it’s planned to add some properties (
column-gap
androw-gap
) to manage this. Similar to what we already have in multi-column withcolumn-gap
.Thanks for enlightening me on “fr.” I’m currently reading Rachel Andrew’s book, CSS3 Layout Modules (2.0), and was puzzled by what “fr” could possibly stand for. I’m bookmarking this article as a refresher once I finish the book!
As always nice article! For more on CSS-Grid Layout Module, check out Rachel Andrew her site has some more up to date examples. It demo’s grid-area, span, grid-templates
This is an exact grid system, if we implement, it can easily solve the layout issues and will be neat on all devices.
Any ETA on when exactly the grid layout will be accepted by Gecko/WebKit browsers?
Why the hell isn’t this widely supported yet?
;(
Who cares?! If there’s browsers not supporting this, too bad for them. But we as developers can’t stay behind and support old browsers.
Your time has come!
@Riyaadh Fakier, would be nice to not have to support legacy code and older browsers but a vast majority of enterprise developers don’t have that luxury ;-p
yeah, I feel ya, if you look at bugzilla you can see that Mozilla is actively working on it. Sadly no eta from what I can find. Hope IE and Safari get on board, its a nice feature and will cut down on the size of any framework sugar you may use or not use one at all.
Funny thing about that… IE 10+ is currently the only browser that supports grid layout, so we can thankfully check them off of our list. :D As I understand it, Microsoft was the major player behind this standard. Basically, they took their WPF grid layout and ported it to the web, which is why they are so far ahead. They already had the code. Anyway, I think mainline chrome supports it behind the experimental flag. Really, I think we’re waiting on Safari and Mozilla at this point. CSS grid will be a wonderful thing when we can finally use it.
Could you please update this article to include the unprefixed versions of these properties in the demo code? Chrome actually does support CSS Grid Layout, you just need to enable the “Experimental Web Platform Features” flag first.
Here’s a pen of part of this article with the prefixes removed:
Is Grid layout system developed by microsoft, as we are seeing its support on IE10+ browsers
Every browser supports this grid property?
No, see the “Browser Support” section – no browser supports this except IE10 (and I’m guessing Edge?)
Would be nice if the examples could be updated with unprefixed properties, which now do work in chrome behind a flag.
Is there a polyfill for this module yet?
https://github.com/FremyCompany/css-grid-polyfill
So, how would one go about making full-width background colors on headers and footers while still maintaining a max/min width on the (centered) content.
That is a very common layout-pattern; I’d like to see it reproduced with grids?
Maybe this writeup will be helpful: https://cloudfour.com/thinks/breaking-out-with-css-grid-layout/
The ‘grid-template’ shorthand has been recently removed from the spec draft in favor of ‘grid’ super-shorthand: https://bugzilla.mozilla.org/show_bug.cgi?id=1253529#c0. Shouldn’t the article be updated again?
Thanks SelenIT. I’ve updated the article. I’ve removed
grid-template
and all references to it, and I’ve expanded ongrid
a bit.BTW, grid-template is back since a while ago and will be shipping on browsers: https://drafts.csswg.org/css-grid/#explicit-grid-shorthand
Probably it should be re-added to the article.
I brought it back.
I am curious.. What if much like photoshop you wanted to display like in layers, one item in grid in front of another item in grid?
i could not find the video on this page can anyone send me the link to the video?
Best tutorial ever, thank you :)
You’re welcome. Glad you found it helpful!
Hi , In your first diagram explaining about template rows and template columns, isn’t rows supposed to run from left to right and the column from top to bottom . It seems like you did the opposite way . I don’t know if That’s how grid works if so then can you specify ? Thank you
Hey Yasir! The diagram shows the grid lines for columns and rows. So, the labels running from left to right are marking the column lines but the lines themselves go top to bottom as columns do. Same deal for rows, which are marked from top to bottom while the lines run from left to right.
I love the Grid Layout. But, but, but reality is it’s not supported well. How much time (years) you think it will take so we can use it across the most popular web-browsers?
I am actually curious about the same thing.
I’ve been thinking the same thing, and it appears that support has in fact diminished since 2014-ish when these articles were written. http://caniuse.com/#feat=css-grid states that FF/Chrome have no intention of supporting it, Safari has left it behind and microsoft has gone to prefixing it.
As it’s not supported by default in any browsers at the moment caniuse.com will show it as not supported, but this page shows a more accurate state of play:
http://gridbyexample.com/browsers/
Hopefully 2017 will be there year this gets supported by default.
As someone who has used WPF / Silverlight Grids a lot and can’t wait to use CSS Grids, I’m curious about the following:
Can a column or row be defined that sizes to the minimum required for the width or height of its children? From the article it looks like ‘auto’ means *-sizing in WPF speak, meaning take up all available space, not the minimum amount of space required which is what Auto-sizing means in WPF.
Is it possible to use minimum / maximum width settings on grid tracks if they are dynamically sized, irrespective of children? EG you want a column that stretches to fit available space but should have a minimum width of 100px even if empty.
For the minimum required width or height you can use
min-content
(ormax-content
for the maximum):E.g.
grid-template-columns: min-content 200px max-content;
About the minimum-maximum size settings, you could use
minmax() function
.E.g.
grid-template-columns: minmax(100px, 1fr);
0fr worked for me, for both min height and width.
Interesting article.
if you’re looking for a super simple Responsive CSS Grid, check this one out:
https://codecanyon.net/item/responsive-html5-css-grid/4928861?ref=CSSGrid
Lee.
I can’t help but notice from the spec that there seems to be a lot of similarities with this and the much maligned table layout. Was using tables for layout just so hated because it was meant for data, not layout?
Yes. Tables have historically been pretty useful for layout (prior to Flexbox there were some layouts that couldn’t be accomplished without tables) but it made no sense semantically.
This grid system its just like wpf but more flexible for people that have worked with wpf its easy to understand and it help to move to new tecnology like asp.net core.
Great introduction!
I found one (well known) issue:
If you want to use % value for height of a child inside a grid-cell, you have to set height:100% for the cell. Otherwise the height of the viewport is taken. You may know this behaviour from body{ height:100%;}
I really can’t wait for this spec to become standard.
Also, I must have a problem with github because every single blog talking about css grid forwards to Remy’s PF, but I am unable to get a result with those browsers that don’t have the flag.
Maybe I just don’t understand which one, in github, is the actual .js file to use…
Ah, Chris, great post anyway!
Anyone knows of a possible malfunction of grid-column-gap/grid-row-gap in François REMY’s polyfill?
Or it’s me? :-)
Awesome. I hope this specs gets out soon and it is adopted by browsers fast. Then there would be no CSS haters.
Great article! It’s just a bit confusing in some places, like under justify-items where it uses
column axis
to refer to the horizontal axis and other places where it usesrow-axis
to refer to the vertical axis. The images clarify the terms but changing that would make things easier.Fantastic resource, anyway.
I might be wrong, but I think that “column axis” might be able to mean either “horizontal axis” or “vertical axis” depending on the writing mode.
Hi there.
How is this better than the already available Flexbox standard?
Really? Defining areas and refer them to BY NAME is not enough for you? :-)
Because flexbox is designed for 1 dimensional layouts. Css grid is for 2 dimensional layouts
https://rachelandrew.co.uk/archives/2016/03/30/should-i-use-grid-or-flexbox/
Is it me or does chrome not support
grid-template-columns and grid-template-rows even with the experimental flag on?
Hi,
Thanks for a great article.
I think that order of the arguments of the shorthand
grid-gap
are reversed, it should berow column
instead ofcolumn row
From MDN:
I tried in both Firefox and Chrome and this is the way they do it.
You’re right it’s row first, column second. I got that updated.
Two small remarks:
Actually you can begin and end the value of this property with line names.
This doesn’t mean the cell will stay empty – it just doesn’t belong to a named region. You can still fill it with content, though.
Great info, but I seem to be having an issue getting rows to dynamically resize based on content when using firefox.
Is this a known issue? Is there a workaround I should be using?
Thanks in advance,
–Chris
CSS Grid Layout Module Level 1 is now (as of Feb 9th 2017) W3C Candidate Recommendation :-)
Yupeeeeee!!!
I used this successfully with
vh
attribute to define row heights. Eg.This gave me a nice footer in the bottom.
This would be a great addition to use hand-in-hand with flexbox – each serving their own purpose. I suppose you could easily use css to change a grid into a flexbox based on media queries. The grid gives us a reason to build our website kind of like back when sites were designed using tables. The only reason why we still don’t to that today is because using the table tag paints you in a corner, whereas the grid is based on css – not a tag (in addition to being non-mobile-responsive). Please let me know if anyone disagrees.
Hello, there is an issue with the axis descriptions for some of the alignment properties. The ones for justify-items and align-items are correct but the remaining 4 are not. The justify-* properties are aligned along the row-axis (inline axis) and the align-* properties are aligned along the column-axis (block axis).
Correct – and fixed – thanks Chen!
The text inside the cell doesn’t start from new line according to the grid size, but expands outside the grid and makes vertical scroll…
Awesome article. Thanks for this cookbook. But I have one concern. It is clear that you can use px, maybe EMs and REMs too, but what about calc()? Can you use it to define dynamic columns?
I always used the flexbox’s guide…
Now, you did this wonderful guide
Thanks Chris!!
*Cody House
Might be silly question but I am somewhat confused. Say if I have a single page consisting of 3 columns and 2 columns and full width layouts, for instance something like this:
How will this be defined in grid?
Ps. I can’t ge the markdown working correctly :| Help? :)
great guide, but it is missing the auto-fill and auto-fit options for repeat(), could you please add those?
https://drafts.csswg.org/css-grid/#auto-repeat
Awesome article, but one quibble. CSS grids is a 3D layout system once z-index is thrown into the mix. This allows background elements to be attached according to the grid lines.
How can I make elements square?
if I have
Can I make the Row heights match the columns widths somehow?
Yes you can.
How can you use grid-auto-flow to make the unexpected children invisible instead of positioned with row | column | row dense | column dense ?
Hi friends,
i have a grid layout
this, good, and the divs alright,
but if i hide the first column with javascript, the second column take te position of the first.
Ex:
When hide the div 1, the div 2 it remains as:
and not this
exist possibility of fix this??
I have the same page whith flexbox and works, but not with grid.
Hello.
I use following CSS:
And now I want to have the content (e.g. navigation) of the footer at the bottom of the footer area. I have try it with
align-self: end;
but it doesn’t make what I need.Hope someone can help.
Excellent article. I’m sure I’ll wear this one out like i have the complete guide to Flexbox. Simple question, does anyone know if you can outline the grid? I feel that would go a long way to demystifying this as I’m learning.
Bob,
This is a tool in firefox that will help you see the grid.
It is called the grid inspector and here are few links to get you started on your CSS Grid Layout path:
https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts
Jen Simmons has a nice video talking about the Grid Inspector Tool
Robert DiBlasi
We all learn by sharing what we know
http://www.cssdisplaygrid.com (coming soon!)
Thanks Robert. That is a huge help. Now to get the magic Chrome extension gnomes to make one for Chrome ;-)
~bob
This is amazing to use and very informative. Its so easy to make layouts, when you get the knack of it I think you could make a header, 3-cols, footer layout in under 4mins.
However while playing around I haven’t grasped how to change the width of a single column. Is there such a thing as a “grid-column-width” sort of property for children?
For example if you have primary, secondary and content columns and wanted to change the width of say the secondary column using the :checked psudo-selector so it slides in and out of view (and updates the width of the content column appropriately) how would you change the width of it?
I’m using “grid-template-columns: 100px 200px auto” which is obviously on the parent and defining grid-areas but I want to change the width of just a single column.
Hope I’ve explained this well enough.
This is a great resource. I’m wondering how people are handling dynamic row height on resize of the view port. As far as I can tell there is no way to keep the proportions of the grid cells.
Amazing article just added to my references list. Thanks!
Thanks for this very useful article!
I have a question about styling grid rows > in this case altering background color each row.
I made a ul > li list with a lot of items. The col count depends on the width of the viewport. Max. 5 cols on witdh more than 1200px, 1 col on smartphone. Now I need dynamic function to alter the background color for every even/odd row. How can I do this?
Well, when on viewport 1200px + I have 5 cols. If I want to have another background color for the odd rows I can write CSS something like this >
.cols li:nth-child(n+6):nth-child(-n+10)
But here I have to define each row by it’s own code. Is there another solution via CSS or do I have to use JS to add classes dynamically?
thx, Tom
Why css grid method doesn’t work when I apply masonry js?
Can you answers questions about changing width/height columns and rows?
What about responsive and mobile first? We don’t really need grid for mobile view, only apply grid for higher resolutions right?
you can control responsiveness through media queries and mutate the grid dynamically
This has been and will continue to be enormously helpful. Thank you!
I’ve made a Chrome extension to perform CSS grid inspection.
looking for some feedback and corner cases
https://chrome.google.com/webstore/detail/gridman-css-grid-inspecto/cmplbmppmfboedgkkelpkfgaakabpicn
How do you add fallback for Opera Mini & I.E?
How do you add href tags around objects in the grid? Seems to mess up the height of the objects every time I try it.
Want to see grid lines without an extension?
This is my hack. It’s basically a grid on top of a grid, mirrored. You can comment it on and off.
Is there any way to auto-size elements if there are less than the specified in the grid-template-columns?
For example if I have this:
grid-template-columns: repeat(6, 1fr);
But I have only 3 or 5 elements generated into the container element and I’d like have them auto-sized.
How do align and justify treat start/end if document direction is not the default English one? (LTR, top to bottom)
Absolutely outstanding work by all involved on the new CSS-GRID.
So refreshing. GOOD IS HERE.
Sadly,
display: subgrid;
is not widely implemented, and was pushed to level 2 of the spec.I wonder if this guide should be updated to reflect this.
+1
This is something I’m grappling with on a work project right now.
One of the hopes and real benefits I had while digging into css-grid is the concept that a developer would be able to lay out their grid and easily assign deep-nested elements that adhere to the grid. The sub grid system as detailed above and in the MDN docs seems to be a reasonable solution to this problem, but
display: subgrid;
seems to be the bastard-child that was left home while the rest of grid went out for a night on the town….An update on the post reflecting spec support for
subgrid
would be awesome.Yeah, subgrid probably shouldn’t be listed since it was pushed back. display: grid within another grid is working fine for me though.
This got to be one of the best resources out there for CSS grids, but it lacks one of the most important features: the autofill function, which is used to automatically add columns to the layout according to the container width.
This is extremely useful, and combined with the
minmax()
function, it provides a perfect flexbox alternative, even “fixing” the behaviour of the last row on ajustify-content: space-between / space-around
flex container.Here’s a working example at my CodePen
https://codepen.io/facundocorradini/pen/XVMLEq
And of course, a link to the specification
The problem with Grid remains, which is the same issue I’ve been grappling with forever. There is no way to make a multirow grid with an unknown column width. I don’t even care if it’s variable width – I just want it to be the width of the widest child, that would be fine. But this is still impossible to do. You’d think repeat(auto-fill,minmax(xx,1fr)) would do the trick, but it does not. You need to set a fixed width for minmax’s first parameter – and the “min” of “minmax” is a misnomer. You’d think “min” would imply that it’s that pixel width at minimum but potentially more. But that is not true.
So – if anyone can solve this problem, feel free. But I have fought with Grid for endless hours now, and been unable to do this. To me, this is the biggest thing I’d hoped Grid would solve, but alas.
It’s funny how after this much time we’re still using tables, now they are moved from HTML to CSS.
Tables are very powerful. The replacement with divs/floats was just bad. This Grid replacement has more promise in it.
Hey, thanks for this awesome documentation. I have a question about the initial values of
align-self
(https://css-tricks.com/snippets/css/complete-guide-grid/#article-header-id-29) andjustify-self
(https://css-tricks.com/snippets/css/complete-guide-grid/#article-header-id-28). You wrote thatstretch
is the initial value for both properties, but the w3c says it’sauto
. Isauto
=stretch
?What is the difference between auto and fr unit?
fr is free space available in available row or col, and auto depends on the contents
Great article! I’m starting to really, REALLY like CSS Grid (especially if combined with flexbox for the details). I do have a question about grid-area (https://css-tricks.com/snippets/css/complete-guide-grid/#article-header-id-27). Can you specify both the region covered and give it a name, or is it only one or the other?
This article is nice to use as quick referencing tool but I’d highly recommend everyone who’s getting to know css grid to actually read a book about it.
Such as Eric Meyer’s Grid Layout in CSS Interface Layout for the Web or Ahmad Ajmi’s Designing with CSS Grid Layout, or any other really. Books are much more complete and deep than articles, because of volume and the amount of hours they put in to write it.
It is an opinionated recommendation, of course. If anyone knows better books then these to read about CSS Grid, please share.
This is an excellent article, thanks for making it available! I was going through it and happened to notice a minor change that could make things a little clearer. In the grid-gap section, it talks about how this is a shortcut method, and uses , and in the example it uses grid-gap: 10px 15px; which would be a row gap of 10px and a column gap of 15px, but in the example just above this for grid-column-gap and grid-row-gap, it uses the reverse, with a row gap of 15px and a column gap of 10px. So, changing the example for the grid-gap to be grid-gap: 15px 10px; would match the other examples.
Hmm.
A quick skim shows possibiltities. I can see this as a big win for things like catalogs.
Currently I do a lot of web pages for my home business site (tree farm) like this:
image reference
caption
Text flow of article
Another paragraph of article
This text is in a box in much larger type with a distinct font
Continue on with the article flow.
The effect on a desktop browerser at normal widths is that I have left side column menu (25%). The main article flow is justified at 65 characters. This is the maximum line length for easy reading. As the screen narrows, the margins shrink, but the line length doesn’t. At a certain narrowness corresponding to phone sizes, image divs take up the full width, and text flow leaps over them.
This works — sort of. All widths are defined in either percents (containers) or rems (text) I have to be careful about having two images too close or I get them stacking on top of each other.
Article flow is subject to frequent updates. I want images to be reasonably near a given paragraph. I want articles to partially flow around images. Article length can vary from 200 words to 3,000. Does grid design give me an advantage over my styled floating divs?
fantastic article, thanks!
…but shouldn’t the expanded code from the repeat() example be
[col-start] 20px [col-start] 20px [col-start] 20px 5%
instead of20px [col-start] 20px [col-start] 20px [col-start] 5%
Yes, thanks!
Please discuss auto-fill and auto-fit …. Really enjoy your site!!!
I’m new to HTML & CSS. I’ve spent years working with WYSIWYG and my brain is fried with trying to learn this, cause there appears to be so much that I have to learn. I’m trying to do the simplest of grids. 3 columns, 10 rows. The page I’m trying to fix is at diyalarm.net/lyricprice.html Each box will contain a pic of an item for sale, a price for the item and a paypal button. If I can just lay out my grid, I can probably figure out the rest. Is there a cheat sheet anywhere, where I can copy and paste the basic code? While I’m asking, is there anyway to auto layout, more like WYSIWYG?
You can make this grid structure simple or just grid in grid mode, way?
https://ibb.co/fE9knd
Hey, is there anyway to interact CSS Grid with the child nodes of an SVG tag? Trying to make a dynamically generated bar graph using Vue and Grid and I’m having difficulties trying to set them in cells. Asking for a friend…
Well written. Easy to understand! Thanks for the great article!
Great review of the possibilities of the grid property. Pinned up !
Excellent article! I came hoping to find content for auto-fit / auto-fill. However I’ll still be using this as a reference, thanks!
Display grid template not working in ie or safari can you please help.?
.grid-container{
display: -ms-grid;
display:grid;
grid-template-columns: 25% 25% 25% 25%;
-ms-grid-columns:25% 25% 25% 25%;
}
.grid{
border: 1px solid #edeaea;
transition: .6s ease-in-out;
-ms-filter: “progid:DXImageTransform.Microsoft.Shadow(Strength=2, Direction=0, Color=#E8E8E8)”;
-moz-box-shadow: 0 1px 2px 1px #e8e8e8;
-webkit-box-shadow: 0 1px 2px 1px #e8e8e8;
box-shadow: 0 1px 2px 1px #e8e8e8;
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=2,Direction=135,Color=#E8E8E8);
background-repeat: no-repeat;
background: #fff;
min-width:300px;
height: 209px;
margin: 30px 10px;
}
Hey there! It kinda depends on what’s going on in the HTML as well, but looking at this example, it looks like .grid is a child of .grid-container. If that’s the case, then .grid will take up the entire four columns that are defined in in .grid.container. If you’re planning on putting children inside of .grid, then you’ll want to set the grid properties there instead so the children can lay out on the grid tracks accordingly.
IE can be a tricky one. Here’s a full series that might help:
Awesome guide!
Such a great post. I just did some online tutorial and needed a refresher/summary. And this post did it for me. Thanks a lot!
I am looking to move my website away from front-end frameworks and I wonder if CSS grid will help with that but then again all I need bootstrap for is the navbar and grid system.
It is easy to understand the span value for grid-column-end and grid-row-end – it starts from the respective start lines.
Could you explain how it is defined for the grid-column-start and grid-row-start properties?
I didn’t try all combinations or all browsers or browser versions, but when grid--start and grid--end are both “span number”, it seems the first one wins, in FF62. It is certainly not clear here what should happen in that case, or other combinations of span number and span name.
What about minmax? I think there should be some talk about that since its a very handy unit used exclusively with grids.
I found a game to practice the CSS grid layout: http://cssgridgarden.com/. There are a couple of challenges to test all grid properties. I hope this will help you get started with Grid.
I can not believe that I’m back to this great article after 3 years now. Funny how the comments are complaining about browsers not supporting the GRID… well.. they are now !
Edge 42 doesn’t understand place-self so I have needed to use align-self and justify-self together.
I wish there was a changelog which shows what parts of the article have been changed. I love that it keeps updating so that it’s always up-to-date, but it would be nice to see what’s new.
I use wayback machine to compare old and new page to figure out what changed
I’m trying from many days to learn the CSS Grid System. There are many online articles about these topics. but those are not easy for me. Now, I found something best. what is easy to understand.
Thank you for the great article.
This is my go to grid guide whenever I am drawing css grids, however can you add “auto-fit” and “auto-fill” attributes to grid size too? thanks in advance
Hello,
add please on grid-column and grid-row information,
that it can target from the end column or row with negative index.
ie: you want last row to span from first to last column;
then you do this on a grid element:
Aligns a grid item inside a cell along the block (column) axis (as opposed to justify-self which aligns along the inline (row) axis). This value applies to the content inside a single grid item.
It was a really helpful and complete article on CSS grid, Thank you.
but I have a question:
shouldn’t it be “in a single grid cell” instead of “in a single grid item”?
Thank you for the guide! This is always super helpful!
I noticed, however, there’s no mention of
order:
? Is that on purpose or an oversight?Agreed. This is an excellent guide. However, to make it “complete”, including the order attribute would be helpful. Especially since this article comes up high on SERPs.
Thanks!
Thank you very much for this guide. I find it really helpful. It is very nice that we can use a grid layout with a css standard these days. You can see it back in a lot of frameworks in all sorts of ways. I wonder if that can be standardized too. Like if we speak about “span_3” a element will span 3 columns, and if you say “md:span_3” it will span 3 columns for “medium screens”.
That concept could be translated to .scss like:
$sizes: xxs, xs, md, lg, xl;
@each $size in $sizes {
.#{$size} {
@include breakpoint(#{$size}) {
$span: 0;
@while $span < 12 {
$span: $span + 1;
&:span_#{$span} {
grid-column: span #{$span};
}
}
}
}
}
which generates the needed classes.
One of the best website to learn CSS. thank you so much!
I’m not clear on how you wrap content around a grid item. For example, imagine a layout with a block and a block. The sidebar should float right, and the top of should be the top of . However, if the content of is longer than the content of , the content from main should take up the full width of the container. Essentially the is a grid item floated right, but the item isn’t a grid item? Is that how it works? Any insight you could provide would be greatly appreciated.
According to MDN and experimentally in Firefox, place-items syntax should not have a / between the two parameters.
I am on the introduction (after browsing the site yesterday) and I already felt the need to leave a reply; love this. I am new to CSS Grid and this entire site is pleasant, easy to understand and the narrative is on topic and friendly. Looking forward to picking up Rachel Andrew’s book.
Gonna make a periodic table with this!
Could you
Explain the difference between 1fr and 2fr?
The reason for me to ask this question is because the way I see fr is the following:
× /
Now each column or row’s share of the leftover space. If you can’t determine what you are getting by ONE FRACTIONAL UNIT. What I really want is if I put 1fr and 2fr what is the difference between them. I can’t get my head round the not knowing what 1fr is because it’s so is 2fr 2*. I hope that you can understand where I am coming from and can help me with this issue.
Marc Dearden
The fr unit is a fraction of the leftover space, relative to the other tracks sized in fr units. Thus, 2fr is twice the size of 1fr, and both are relative to whatever is left over from explicitly-sized tracks.
Powerful explanation. i like your diagrammatic illustrations, they help to understand the concepts. Great job Chris
Thanks a ton for this tutorial. I finally understand Grid layouts.
On Properties for the Parent (Grid Container)
Is display:grid-inline instead of display:inline-grid ?
inline-grid
is correct. Here’s the spec.Hello, I don’t understand the description of GridTrack and Grid Area in the Terminology section, is that correct?
” grid track between the second and third-row grid lines.”
(but shows 2 lines one of them completely yellow)
“The total space surrounded by four grid lines”
(there is no total space surrounded anywhere on the example pic)
Can somebody explain to me what I understand wrongly?
Thank you.
I just learned that there is another function for css grid called fit-content. This is not mentioned on this page. I believe it should be.
This is an exceptional website for learning css. I come to this website with a problem but when I am leaving I have a smile on my face.Thank You.
it would be great if you break down the new concepts one at a time with its accompanying exmaple & visual-aid not condensing them altogether … every time i read a new concept it just sounds like a condensed utter nonsense till i read the following
Chris, first off, thank you so much for this detailed post. Really really helped me learn about Grid.
I used it to create a flexible layout for my WordPress blog.
Well, I ended up opening the website on IE11, only to find that it’s all messed up.
So, I came here to ask for your opinion. Do you think it’s time to completely drop support for IE 11 and other older outdated browsers? As far as I have researched, my website stats say that I really don’t have any users using IE. About 70% of my traffic comes from Chrome, Firefox, Safari, and Edge (in that order).
Should I just stop worrying and opt for Grid or still focus on backwards compatibility?
/* UPDATE */
So, I ended up reading a lot about Grid and IE. Thanks to your complete series on the topic, MDN’s documentation, and Autoprefixer, I figured out an easy solution.
To everybody out there who’s reading this article, you must go through the Grid series published here. It’s everything you will ever need when dealing with IE and Grids. On top of that, don’t be demotivated (I was on the verge of giving up) and don’t hesitate to use CSS Grid for your project. It is actually very wonderful! No more ugly floats or complex structures. Phew!
Again, thank you CSS Tricks, and everybody on the team who put so much effort into this article, the series, and the Flexbox article.
A very complete presentation of CSS grid that needed to be written in plainer language that the standard. Well done. However, it appears to me that this Grid thing is able to do pretty much anything anybody has ever wanted to do in presenting “things” arranged in a grid. However, it also appears to be too complex for anybody to actually use unless they specialize in only doing grids and nothing else so they can keep track of all the optional bits and the shortcuts (which can often make it much easier to understand). Or maybe they specialize in one “type” of grid.
Perhaps, it would be more useful to present use cases that can be used by somebody who occasionally sees a need to use grids, in order to help implement particular popular situations in addition to what appears to be the very complete description of “everything”. I can’t see a lot of people holding on to all the somewhat non-intuitive terminology to implement a grid layout from time to time.
Totally hear you. There is indeed a level of complexity that’s tough to grok, at least initially. At the same time, I’ve found that — just like flexbox — Grid is much more intuitive the more you use it. For me, it was practicing, and knowing the difference between, the different approaches for defining grid areas and tracks.
Pairing documentation to use cases is interesting. While this isn’t exactly that, there are some starter grid layouts here on the site that can get you thinking that way.
The trick to mastering grid is: pick the one syntax you are comfortable with and stick to it. The shorthand syntax descriptions in MDN and W3C are obtuse, to say the least. To get the basic layout, I use that grid shorthand only, and assign all my div ids using grid-area. The pattern is:
body {grid: “cell1 cell2” rowheight “cell3 cell4” rowheight / colwidth colwidth}
#selector1 {grid-area: cell1}
This is all you need to start.
As the definition for “Grid Track”, it says: “The space between two adjacent grid lines.”. Are you sure that’s correct?! The example shows the space between column grid lines 1 and 4, which are obviously not adjacent.
Am I missing something here? Or is the definition incorrect?
Yes, that definition is correct per the spec:
I have a situation here where I need to have 4 columns with the same width and have the gaps with a fix size of 1rem. Well, I have defined the grid items with 25% but what’s happening is that the grid is exceeding the width of the container because it’s adding the gaps values. I tried setting the grid items with the value ‘auto’ and some columns just got shrunk and I need them with the same size. How can I achieve this result? It’s a product grid for an online shop.
Try using “1fr” instead of “25%”. I think that should do it.
If multiple lines share the same name, they can be referenced by their line name and count.
.item {
grid-column-start: col-start 2;
}
I don’t understand this part pls explian it or pls give me a link so that i can understand properly.
Hey! This is my understanding (and I could be wrong, of course). Let’s say we have five grid column track lines. We want the first three to represent the main content of our layout, so we name them
main-col
. Now, we have three lines that have the same name, which is great for identifying the content of that column, but no clear way to distinguish between the two when it comes to setting elements on those track lines.But since grid tracks lines have implicit numbers, we can use those along with our
main-col
name to properly lay things out while distinguishing between the two. So, if we want some thing to start from the secondmain-col
track line, we can do that like this:In other words, it’s basically a nice little affordance for naming. It might not always come in handy, but it certainly will if you prefer a slightly simpler convention for naming grid track lines.