CSS Grid, from first line to last

A walkthrough in three stages. Draw your first grid, learn to put items exactly where you want them, then build layouts that adapt on their own. Every box on this page, including the ones to the right, is placed with the code it's showing.

grid-column: 5 / 7
grid-row: 2 / 4
grid-area: 2 / 6
an empty cell
row 3, col 6

Meet the grid

What grid is, how to turn it on, and how columns, rows and the gaps between them work.

Why grid exists

Flexbox arranges items along one direction at a time: a row, or a column. That's perfect for a navigation bar or a row of buttons. But a page layout has two directions at once. The sidebar has to line up with the footer, the cards in row two have to line up with row one.

CSS Grid handles both directions together. You describe the rows and columns on the parent, and the children fall into the cells. The parent is called the grid container and its direct children are grid items.

Your first grid

Two lines of CSS create a grid: display: grid turns it on, and grid-template-columns says how many columns there are and how wide each one is. Everything else is optional. Move the controls and watch the code on the right change with the layout.

Your CSS

Notice that you never told item 4 to start a new row. When the columns run out, grid wraps to the next row automatically. This is called auto-placement, and it's what you get until you place items yourself in stage 2.

The fr unit

fr means "fraction of the leftover space." Grid first sets aside anything with a fixed size (like 200px) and the gaps, then shares whatever remains between the fr tracks in proportion. 2fr 1fr gives the first column twice as much as the second.

grid-template-columns: 1fr 1fr 1fr;
1fr
1fr
1fr
grid-template-columns: 2fr 1fr 1fr;
2fr
1fr
1fr
grid-template-columns: 140px 1fr;
140px, always
1fr takes the rest
grid-template-columns: repeat(4, 1fr);
1fr
1fr
1fr
1fr

repeat(4, 1fr) is shorthand for writing 1fr four times. You'll use it constantly.

Rows you define, rows grid creates

grid-template-rows defines rows up front, the same way columns work. But you often don't know how many rows you'll need, because it depends on how much content there is. Rows that grid creates on its own are called implicit rows, and you size them with grid-auto-rows. Try the "Row height" control above: minmax(60px, auto) means "at least 60px, but grow if the content needs it."

Finally, gap sets the space between tracks. It never adds space around the outside edge, only between items. You can set them separately with row-gap and column-gap.

Check yourself

A container is 900px wide with grid-template-columns: 300px 2fr 1fr and no gap. How wide is the last column?

200px. The fixed 300px comes out first, leaving 600px. That's shared as 3 fractions (2 + 1), so each fraction is 200px. The middle column gets 400px and the last gets 200px.

You have 3 columns and 8 items. How many rows does grid make?

3 rows. Two full rows of 3, plus a third row holding the last 2 items. All of them are implicit rows unless you set grid-template-rows.

Does gap: 20px add space between the grid and its container's border?

No. Gaps only go between tracks. Use padding on the container for space around the outside.

Go to stage 2

Place things precisely

Stop letting grid decide. Use line numbers and named areas to put each item exactly where it belongs.

Think in lines, not cells

The key idea in stage 2: grid numbers the lines between tracks, not the tracks themselves. A 4-column grid has 5 vertical lines, numbered 1 to 5 from the left. It also has negative numbers counting from the right, so -1 is always the last line. That's handy when you want something to stretch to the end without knowing how many columns there are.

The blue item below starts at column line 2 and ends at column line 4, and it runs from row line 1 to row line 3.

2 / 4
The blue item
.item {
  grid-column: 2 / 4;
  grid-row: 1 / 3;
}

/* the same thing, other ways */
grid-column: 2 / span 2;
grid-column: 2 / -2;

Placing items yourself

grid-column takes a start line and an end line separated by a slash. Instead of an end line, you can write span 2 to mean "cover two tracks." Pick an item, then type a value or tap a shortcut. Items you haven't placed keep flowing into whatever cells are free.

Shortcuts
Your CSS

Try placing two items on top of each other, like A at 1 / 3 and B at 2 / 4 on the same row. Grid lets items overlap. The one later in the HTML sits on top, unless you change it with z-index.

Naming areas

Line numbers are precise but hard to read later. grid-template-areas lets you draw the layout as a little text map. Each quoted string is one row, and each word is one cell. Repeat a name to make an area span multiple cells. Use a . for an empty cell. Then give each item a matching grid-area name.

Edit the map below. Two rules to keep in mind: every row needs the same number of cells, and every area has to be a rectangle.

Layouts
header
nav
main
aside
footer
Your CSS

Check yourself

How many vertical lines does a 6-column grid have?

7. There's always one more line than there are tracks.

What's the difference between grid-column: 2 / 4 and grid-column: 2 / span 4?

The first ends at line 4, so it covers 2 columns. The second covers 4 columns, so it ends at line 6.

Why is "a a" "a b" "a a" an invalid area map?

Area a wraps around b in an L shape. Every named area must form a single rectangle, so the browser rejects the whole declaration.

Go to stage 3

Master the grid

Responsive layouts with no media queries, alignment, gap filling, subgrid, and a final challenge to prove it.

Responsive without media queries

This one line is probably the most useful thing grid can do:

grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));

Read it from the inside out. minmax(160px, 1fr) means each column is at least 160px but can grow. auto-fit means "fit as many of those columns as the space allows." As the container shrinks, columns drop onto new rows by themselves. Drag the width slider.

To see the difference between the two keywords, choose "2 items" and make the container wide. auto-fill keeps the empty column slots, so the items stay narrow. auto-fit collapses the empty slots, so the two items stretch to fill the row.

Aligning items inside their cells

An item doesn't have to fill its cell. justify-items aligns along the row (left to right) and align-items aligns along the column (top to bottom). Both apply to every item. To override just one, set justify-self or align-self on it, or both at once with place-self.

Your CSS

Filling the holes with dense

When items span different sizes, auto-placement can leave gaps: an item that's too wide for the remaining space jumps to the next row and leaves a hole behind it. grid-auto-flow: dense tells grid to go back and fill earlier holes with smaller items that come later. Watch the numbers when you turn it on.

Use dense for things like photo galleries, where order doesn't matter. Avoid it when order does, because the visual order stops matching the HTML order, which confuses keyboard and screen-reader users.

Subgrid: lining up nested content

A grid item can be a grid itself, but normally its inner tracks know nothing about its parent's tracks. That's why card titles of different lengths push the text below them out of line. grid-template-rows: subgrid makes a card borrow its parent's rows, so every title shares a row height with its neighbors. The dashed outlines show where each title sits.

Starter

For trying things out on one small project.

Team plan with shared workspaces

Invite people, share files and set permissions for each project.

Business

Everything in Team, plus audit logs.

The key lines
.cards {
  display: grid;
  grid-template-columns:
    repeat(auto-fit, minmax(190px, 1fr));
}

.card {
  grid-row: span 3;   /* title, text, button */
  display: grid;
  grid-template-rows: subgrid;
}

Final challenge

Rebuild the target layout on the right side using only CSS. The board is 240px tall and you can target .board, .header, .nav, .main, .ads and .footer. Your version updates as you type. Hit "Check my layout" when you think it matches.

Target

header
main
ads

Yours

header
main
ads
Hint: the measurements

There are 3 columns. The middle one is three times as wide as each side column. The header row is 48px, the footer row is 40px, and the middle row takes everything else. The gap is 8px. The nav is in the first column and runs down through the footer row.

Show a solution
.board {
  display: grid;
  grid-template-columns: 1fr 3fr 1fr;
  grid-template-rows: 48px 1fr 40px;
  gap: 8px;
}
.header { grid-column: 1 / -1; }
.nav    { grid-row: 2 / 4; }
.footer { grid-column: 2 / 4; }

/* or with areas */
.board {
  grid-template-areas:
    "header header header"
    "nav    main   ads"
    "nav    footer footer";
}
See the cheat sheet

Cheat sheet

Everything from the three stages in one place.

PropertyGoes onWhat it does
display: gridContainerTurns the element into a grid. Stage 1
grid-template-columnsContainerSets how many columns there are and their sizes. Stage 1
grid-template-rowsContainerSets the rows you know about up front. Stage 1
grid-auto-rowsContainerSizes rows that grid creates automatically. Stage 1
gapContainerSpace between tracks, not around the edge. Stage 1
fr, repeat()Track sizesShare leftover space; repeat a pattern. Stage 1
grid-column, grid-rowItemStart and end lines, or span n. Stage 2
grid-template-areasContainerDraws the layout as named rows of cells. Stage 2
grid-areaItemPuts an item into a named area. Stage 2
minmax(), auto-fit, auto-fillTrack sizesColumns that wrap on their own as space changes. Stage 3
justify-items, align-itemsContainerAlign every item inside its cell. Stage 3
place-selfItemAlign one item, overriding the container. Stage 3
grid-auto-flow: denseContainerBackfills holes left by auto-placement. Stage 3
subgridNested gridMakes a child grid reuse its parent's tracks. Stage 3