A Complete Guide to Grid

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 elements children (which become Grid Items).

This article was ported over from Chris House's guide, by Chris himself, who is keeping both up-to-date.

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.

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.

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!

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

Opera

Firefox

IE

Edge

Safari

57

44

52

11*

16

10.1

Mobile / Tablet

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.

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

Grid Area

The total space surrounded by four grid lines. A grid area may be comprised 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.

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

subgrid - if your grid container is itself a grid item (i.e. nested grids), you can use this property to indicate that you want the sizes of its rows/columns to be taken from its parent rather than specifying its own.

.container {
display: grid | inline-grid | subgrid;
}

Note: column, float, clear, and vertical-align have no effect on a grid container.

grid-template-columnsgrid-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)

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.

That'll create a grid that's four columns wide by three rows tall. The entire top row will be comprised of the header area. The middle row will be comprised 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.

justify-items

Aligns the content inside a grid item along the row axis (as opposed to align-items which aligns along the column axis). This value applies to all grid items inside the container.

Values:

start - aligns the content to the left end of the grid area

end - aligns the content to the right end of the grid area

center - aligns the content in the center of the grid area

stretch - fills the whole width of the grid area (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 the content inside a grid item along the column axis (as opposed to justify-items which aligns along the row axis). This value applies to all grid items inside the container.

Values:

start - aligns the content to the top of the grid area

end - aligns the content to the bottom of the grid area

center - aligns the content in the center of the grid area

stretch - fills the whole height of the grid area (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.

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 row axis (as opposed to align-content which aligns the grid along the column axis).

Values:

start - aligns the grid to the left end of the grid container

end - aligns the grid to the right end 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

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 column axis (as opposed to justify-content which aligns the grid along the row axis).

Values:

start - aligns the grid to the top of the grid container

end - aligns the grid to the bottom 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

grid-auto-columnsgrid-auto-rows

Specifies the size of any auto-generated grid tracks (aka implicit grid tracks). Implicit grid tracks get created when you explicitly position rows or columns (via grid-template-rows/grid-template-columns) that are out of range of the defined grid.

Values:

<track-size> - can be a length, a percentage, or a fraction of the free space in the grid (using the fr unit)

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

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

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:

Properties for the Children(Grid Items)

grid-column-startgrid-column-endgrid-row-startgrid-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

Comments

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)

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!

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.

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?

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

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?

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…

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 uses row-axis to refer to the vertical axis. The images clarify the terms but changing that would make things easier.

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

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.

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.

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?

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.

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 a justify-content: space-between / space-around flex container.

.grid{
/*sets the container as a grid with variable number of columns*/
display:grid;
grid-template-columns: repeat(auto-fill, minmax(150px,1fr));
}

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.

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.