T2 CSS · Lesson 6
Grid
Grids of columns and rows; the fr unit, repeat() and gap; placing items by line numbers and span; whole pages laid out by named areas; grids that make their own rows and fit as many cards as the screen holds; and grid against flexbox.
- make a grid of columns and rows, in pixels and in fr shares
- write columns with repeat() and minmax(), and space them with gap
- place an item by line numbers, and stretch it across columns or rows with span
- lay out a whole page by naming its areas
- let a grid make its own rows and fit as many cards as the screen allows, and choose between grid and flexbox
The back cover
A newspaper page is built on columns of equal width, with headlines that run across several. CSS Grid brings that kind of layout to the web. You draw the columns and rows on a container, and the items take their places in it.
These pages show grids of columns and rows, and the fr unit that shares out the width. They show how to place an item by the grid's lines, and how to lay out a whole page by naming its areas. Then they show grids that arrange themselves, fitting as many cards as the screen can hold.
Before you start
The story: The map of the Fair
The warden spreads out a plan of the Fair on the Tailors' Hall table: twelve stalls in rows and columns, the stage taking two places in the middle, the gate across the whole bottom edge. He wants it on the square's big board, exactly like the paper.
Corin tries with rows of notices, one flex row for each line of stalls. Each row sizes itself, so the stalls of one row no longer sit under the stalls of the row above, and the stage will not stretch across two places.
Meher unrolls a sheet of squared paper. "Rows alone will not do it," she says. "You need rows and columns at once, like this paper. Then say which squares each piece takes."
Flexbox lays things out in one direction at a time: a row, or a column. Many layouts need both at once: a page with a header across the top, a sidebar and a main area, and a footer; a board of cards whose columns line up from row to row. CSS grid is the tool for two directions at once. It builds on these ideas; each has a tiny example.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| A flex container and its items. | display: flex on the parent; children follow. | display: grid works the same way: rules on the parent. |
| Flex rows size themselves. | Each row of cards shares its own space. | Grid columns are shared by every row, so they line up. |
| gap. | gap: 20px between flex items. | Grid has gap too, between rows and columns. |
| Sharing spare space by shares. | flex-grow 1 and 2: one share and two shares. | Grid's fr unit is a share of the spare space. |
| justify and align. | Main axis and cross axis. | Grid uses the same words, for its columns and rows. |
| Semantic page parts. | header, aside, main, footer. | Grid places each one in its own named area. |
| Tables have rows and columns. | A timetable of days and periods. | Grid lays out boxes in rows and columns, for layout instead of data. |
| Squared paper. | Lines across and down make squares to draw in. | A grid's lines are numbered, and items are placed by them. |
| Measuring what was drawn. | getBoundingClientRect(). | Every block checks where each box landed. |
By the end of this lesson you will be able to:
- make a grid of columns and rows, in pixels and in fr shares;
- write columns with repeat() and minmax(), and space them with gap;
- place an item by line numbers, and stretch it across columns or rows with span;
- lay out a whole page by naming its areas;
- let a grid make its own rows and fit as many cards as the screen allows, and choose between grid and flexbox.
In one line
Grid lays boxes out in rows and columns at once, so columns line up from row to row; you need flexbox's container idea, gap and shares, and the HTML step's page parts.
A grid of columns and rows
At a glance
A sheet of squared paper has lines across and down, and you write one thing in each square. A CSS grid is that sheet. You write display: grid on a container, and its direct children become grid items.
The grid-template-columns and grid-template-rows properties draw the columns and rows, called tracks. The items fill the cells row by row, every row shares the same columns, and gap sets the space between tracks. Flexbox lays out one line at a time; grid lays out rows and columns at once.
Take a guess: If a grid has three columns and five items, how many items sit in its second row?
Take a sheet of squared paper. Its lines across and down divide it into squares, and you can write one thing in each square, row by row. A CSS grid is that sheet: you draw the columns and rows on the container, and the items fill the squares.
An element with display: grid is a grid container; its direct children are grid items. Its columns and rows are called tracks, and the square where a column and a row cross is a cell.
<!DOCTYPE html>
<style>
body { margin: 0; }
.board {
display: grid;
grid-template-columns: 100px 200px 300px;
width: 600px;
}
.board div { height: 40px; background-color: gold; }
</style>
<div class="board">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
Checked in Chrome
- three columns starting at 0, 100 and 300; the fourth item starts a new row
- each item takes its column's width
- the fourth item sits on the second row, 40px down
grid-template-columns lists the columns' widths, one value per column: three values, three columns. The items fill the cells in the order they are written, left to right along a row, then on to the next row. Item 4 had no room on row 1, so it started row 2 under item 1, in a 100px cell, because every row shares the same columns.
A memory aid
Flexbox: one line at a time. Grid: rows and columns at once. In a grid, the columns are drawn once on the container, so everything in a column lines up, row after row.
Rows, and gap
grid-template-rows sets the rows' heights the same way. gap puts space between the tracks, never at the outer edges; row-gap and column-gap set the two directions separately.
<!DOCTYPE html>
<style>
body { margin: 0; }
.board {
display: grid;
grid-template-columns: 100px 100px;
grid-template-rows: 50px 80px;
gap: 10px;
width: 600px;
}
.board div { background-color: gold; }
</style>
<div class="board">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
Checked in Chrome
- two columns, 10px apart
- the second row starts at 60: the first row's 50px and a 10px gap
- the rows are 50px and 80px tall
Notice that the items have no height of their own: each fills its cell, as flex items stretch. A grid item stretches to its cell by default, both ways.
Worked example 1
A school's photo board shows six photos in three columns of 150px, with 20px between columns and between rows, each row 100px tall. Write the grid and work out where the fifth photo starts.
What we have: six photos, three 150px columns, 100px rows, a 20px gap
What we need: the grid rule, and the fifth photo's position
The plan: three columns, so photos 4 to 6 are the second row; photo 5 is the middle column
- The middle column starts at 150 + 20 = 170.
- The second row starts at 100 + 20 = 120.
- So photo 5 starts at 170 across and 120 down.
<!DOCTYPE html>
<style>
body { margin: 0; }
.photos {
display: grid;
grid-template-columns: 150px 150px 150px;
grid-template-rows: 100px 100px;
gap: 20px;
}
.photos div { background-color: lightyellow; }
</style>
<div class="photos">
<div>1</div><div>2</div><div>3</div>
<div>4</div><div>5</div><div>6</div>
</div>
Checked in Chrome
- photo 5 starts at 170 across, 120 down
grid-template-columns: 150px 150px 150px; grid-template-rows: 100px 100px; gap: 20px; Photo 5 starts at 170, 120.
Check: the browser placed photo 5 exactly where the arithmetic said.
When you are stuck: grids
display: grid goes on the container; then grid-template-columns lists one width per column.
Items fill cells in order, row by row; when a row is full, the next item starts a new row.
Spaces between tracks: gap, never margins on every item.
Your turn
How many columns does grid-template-columns: 1px 2px 3px 4px make?Tap to reveal
- One value per column.
Four.
A grid has two columns. In which row does the third item go?Tap to reveal
- Fill row by row.
The second row, under the first item.
What is a cell?Tap to reveal
- Where a column and a row cross.
The square where one column and one row cross.
Did you know?
Grid began with three editors at Microsoft
CSS Grid began with engineers at Microsoft. The first W3C Working Draft of the standard, titled Grid Layout and dated 7 April 2011, names three editors from Microsoft Corporation, Alex Mogilevsky, Phil Cupp and Markus Mielke, together with Daniel Glazman of Disruptive Innovations.
Why it fits here: This topic's grid of columns and rows grew out of that 2011 draft.
A grid ignores floats
A grid ignores the old float trick. The Grid standard says float and clear have no effect on a grid item, and neither does vertical-align. The reason is that a grid container is not a block container, so some properties that were designed for block layout do not apply inside a grid.
Why it fits here: It is one way this topic's grid items behave differently from ordinary blocks.
Source: W3C: CSS Grid Layout
In one line
display: grid makes a grid container; grid-template-columns and grid-template-rows draw its tracks, items fill the cells row by row, every row shares the columns, and gap spaces the tracks.
Sharing the width: the fr unit and repeat()
At a glance
A family shares a pizza in slices, not in centimetres. The fr unit shares a grid's width the same way: one fr is one share of the free space, the width left after fixed columns and gaps are taken out. So 1fr 2fr 1fr makes four shares, and the middle column gets two.
The repeat() form writes a track many times: repeat(3, 1fr) is three equal columns. Pixels and fr mix freely, so a 200px sidebar can sit beside a 1fr column that takes everything left over.
Take a guess: If a 600px grid has columns of 200px and 1fr, with no gap, how wide is the 1fr column?
A family of four orders one large pizza: the father gets 2 slices for every 1 the others get. Nobody says "10 centimetres of pizza"; they say "shares". Grid has a unit that works the same way: the fr, short for fraction, one share of the free space.
A fraction of the grid's free space: the width left after any fixed-size columns and the gaps are taken out. 1fr 2fr 1fr means four shares, the middle column getting two.
<!DOCTYPE html>
<style>
body { margin: 0; }
.board {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
gap: 20px;
width: 600px;
}
.board div { height: 40px; background-color: gold; }
</style>
<div class="board">
<div>Side</div>
<div>Main</div>
<div>Side</div>
</div>
Checked in Chrome
- four shares of 140: 140, 280 and 140
- starting at 0, 160 and 460, with the 20px gaps between
Work it out the browser's way. First the gaps: two gaps of 20 take 40 of the 600, leaving 560 free. Then the shares: 1 + 2 + 1 = 4, so one share is 560 ÷ 4 = 140. The middle column gets two shares, 280.
A memory aid
Fixed things first, then shares. The browser takes out every px column and every gap, then splits what is left by fr.
repeat(): the same track many times
repeat(4, 1fr) means 1fr 1fr 1fr 1fr: four equal columns, without writing them out.
<!DOCTYPE html>
<style>
body { margin: 0; }
.board {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
width: 600px;
}
.board div { height: 40px; background-color: gold; }
</style>
<div class="board">
<div>1</div><div>2</div><div>3</div><div>4</div>
</div>
Checked in Chrome
- four equal columns: (600 − 60) ÷ 4 = 135
- starting 155 apart: a column of 135 plus a gap of 20
Fixed and flexible together
Mix px and fr to keep one column fixed and let the rest share: a 200px sidebar beside a main area that takes the remainder, at any screen width.
<!DOCTYPE html>
<style>
body { margin: 0; }
.page {
display: grid;
grid-template-columns: 200px 1fr;
width: 600px;
}
.page > * { height: 40px; background-color: lightyellow; }
</style>
<div class="page">
<aside>Categories</aside>
<main>Products</main>
</div>
Checked in Chrome
- the sidebar keeps 200px; the main area takes the other 400
Why not write the main area as a percentage? Because 75% of 600 is 450, and with the 200px sidebar that would need 650 pixels: the row would overflow. The fr unit always shares only what is actually left, so it never overflows.
fr and % are not the same
A % is a share of the whole container, whatever else is in the row. An fr is a share of what is left after fixed columns and gaps. Mixing % columns with gaps often makes a grid a little wider than its container; fr avoids that.
Worked example 2
A product page is 600px wide: a 250px photo column, then two equal columns for the description and the reviews, with 20px gaps. Write the columns, and work out each width.
What we have: one fixed column, two equal flexible ones, two gaps
What we need: the grid-template-columns value and three widths
The plan: 250px first; the gaps take 40; the remaining 310 split into two equal shares
- Free space: 600 − 250 − 20 − 20 = 310.
- Two shares of 1fr each: 310 ÷ 2 = 155.
<!DOCTYPE html>
<style>
body { margin: 0; }
.product {
display: grid;
grid-template-columns: 250px 1fr 1fr;
gap: 20px;
width: 600px;
}
.product div { height: 40px; background-color: gold; }
</style>
<div class="product">
<div>Photo</div>
<div>Description</div>
<div>Reviews</div>
</div>
Checked in Chrome
- 250 for the photo, 155 for each of the others
grid-template-columns: 250px 1fr 1fr; giving 250, 155 and 155.
Check: the browser drew exactly those three widths.
A path that fails: Writing 250px 50% 50%. The two halves of 600 would each be 300, and with the photo and the gaps the row would need 890px, far wider than the page.
Worked example 3
A school's weekly timetable needs a fixed 80px column for the times, then five equal columns for Monday to Friday, in a 680px box with no gaps. Write the columns with repeat(), and work out a day column's width and where Wednesday starts.
What we have: one 80px column and five equal ones in 680px
What we need: grid-template-columns, a day's width, Wednesday's left edge
The plan: 80px first, then repeat(5, 1fr) for the days; the days share 680 − 80
- The days share 680 − 80 = 600 pixels: 600 ÷ 5 = 120 each.
- Wednesday is the third day, so it starts after the time column and two days: 80 + 120 + 120 = 320.
<!DOCTYPE html>
<style>
body { margin: 0; }
.week {
display: grid;
grid-template-columns: 80px repeat(5, 1fr);
width: 680px;
}
.week div { height: 40px; background-color: lightyellow; border-right: 1px solid gold; }
</style>
<div class="week">
<div>Time</div><div>Mon</div><div>Tue</div><div>Wed</div><div>Thu</div><div>Fri</div>
</div>
Checked in Chrome
- the time column is 80, each day 120
- Wednesday starts at 320
grid-template-columns: 80px repeat(5, 1fr); Each day is 120px, and Wednesday starts at 320.
Check: the browser drew the six columns at exactly those widths.
When you are stuck: fr
Take out the fixed columns and the gaps first; divide what is left by the total number of fr.
Equal columns: repeat(n, 1fr).
A row wider than its container: look for % columns beside gaps or fixed columns; use fr.
Your turn
In 500px with no gap, how wide is each column of 1fr 4fr?Tap to reveal
- Five shares of 100.
100px and 400px.
What does repeat(3, 1fr) mean?Tap to reveal
- Write it out.
1fr 1fr 1fr: three equal columns.
Why does 200px 1fr never overflow, while 200px 75% can?Tap to reveal
- What does fr share?
Because fr shares only what is left after the 200px; 75% is of the whole width.
Did you know?
An fr column keeps room for its content
An fr column will not shrink below its content. The Grid standard says that fr written on its own implies an automatic minimum, as if it were minmax(auto, 1fr). So one very long word can make a 1fr column wider than its share. Writing minmax(0, 1fr) instead gives strict, equal shares.
Why it fits here: It is the fine print of this topic's fr: the shares are fair until the content is too wide to fit.
Source: W3C: CSS Grid Layout
In one line
An fr is a share of the free space left after fixed tracks and gaps, so 1fr 2fr 1fr splits it 1 : 2 : 1 and never overflows. The repeat(n, track) form writes a track n times, and px and fr mix freely.
Placing items by the grid's lines
At a glance
Football players talk about the lines on the grass: from the halfway line to the penalty line. A grid has lines too, between and around its tracks, numbered from 1 at the start. A grid of three columns has four column lines, and -1 means the last one.
Writing grid-column: 2 / 4 places an item from line 2 to line 4, across two columns. The word span covers a number of tracks wherever the item lands, and 1 / -1 runs it from edge to edge.
Take a guess: If a grid has three columns, which two lines does grid-column: 1 / -1 run between?
On a football ground, the lines on the grass are what the players use: "from the halfway line to the penalty line". A grid has lines too, between and around its tracks, and you place an item by naming the lines it runs between.
The lines are numbered
A grid of 3 columns has 4 vertical lines: one before the first column, one between each pair, one after the last. They are numbered from 1 at the left edge. Rows are numbered the same way from the top. Counting from the other end works too: -1 is always the last line.
| Columns | Lines | Numbers |
|---|---|---|
| 3 | 4 vertical lines | 1, 2, 3, 4 (or −4, −3, −2, −1 from the right) |
| n | n + 1 lines | 1 to n + 1 |
grid-column: 2 / 4 reads "from column line 2 to column line 4": the item covers columns 2 and 3. grid-row does the same for rows.
<!DOCTYPE html>
<style>
body { margin: 0; }
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-auto-rows: 40px;
}
.board div { background-color: gold; }
.stage { grid-column: 2 / 4; grid-row: 1; background-color: teal; }
</style>
<div class="board">
<div>Stall</div>
<div class="stage">Stage</div>
</div>
Checked in Chrome
- the stage runs from line 2 to line 4: it starts at 100 and covers two columns, 200 wide
- the stall takes the first free cell, on the left
span: how many tracks to cover
Often you do not care which lines, only how many tracks. grid-column: span 2 means "cover two columns, wherever you land". The item still flows into the next free place, just bigger.
<!DOCTYPE html>
<style>
body { margin: 0; }
.board {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 40px;
width: 600px;
}
.board div { background-color: gold; border: 1px solid white; }
.wide { grid-column: span 2; }
.tall { grid-row: span 2; }
</style>
<div class="board">
<div class="wide">Stage</div>
<div>Stall 1</div>
<div class="tall">Food court</div>
<div>Stall 2</div>
<div>Stall 3</div>
</div>
Checked in Chrome
- the stage spans two of the three 200px columns: 400 wide
- the food court spans two 40px rows: 80 tall
- the others flow into the free cells around them
Across the whole grid: 1 / -1
To make a header or a footer run across every column, whatever their number, write grid-column: 1 / -1: from the first line to the last.
<!DOCTYPE html>
<style>
body { margin: 0; }
.board {
display: grid;
grid-template-columns: repeat(4, 1fr);
width: 600px;
}
.board > * { height: 40px; background-color: lightyellow; }
.title { grid-column: 1 / -1; margin: 0; background-color: gold; }
</style>
<div class="board">
<h2 class="title">The Fair</h2>
<div>1</div><div>2</div><div>3</div><div>4</div>
</div>
Checked in Chrome
- the title runs from the first line to the last: the full 600
- and the four stalls sit together on the row below it
A memory aid
Lines, not boxes. 2 / 4 names the lines on either side, so it covers the tracks between them: columns 2 and 3. And 1 / -1 is always edge to edge.
Worked example 4
The Fair's board has 4 equal columns in 600px with 40px rows. The stage must cover columns 2 and 3 of the first row, and the gate must run across the whole second row. Write the two placements and check them.
What we have: a 4-column grid, a stage over columns 2 and 3, a gate across a row
What we need: grid-column and grid-row for each
The plan: columns 2 and 3 lie between lines 2 and 4; a whole row is 1 / -1
<!DOCTYPE html>
<style>
body { margin: 0; }
.fair {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 40px;
width: 600px;
}
.fair div { background-color: lightyellow; }
.stage { grid-column: 2 / 4; grid-row: 1; background-color: teal; }
.gate { grid-column: 1 / -1; grid-row: 2; background-color: gold; }
</style>
<div class="fair">
<div class="stage">Stage</div>
<div class="gate">Gate</div>
</div>
Checked in Chrome
- the stage covers columns 2 and 3: from 150, 300 wide
- the gate runs across the whole second row
.stage { grid-column: 2 / 4; grid-row: 1; } and .gate { grid-column: 1 / -1; grid-row: 2; }
Check: the browser placed both exactly: the stage at 150, 300 wide, the gate edge to edge at 40 down.
When you are stuck: placing items
Count lines, not columns: a grid of n columns has n + 1 lines, numbered from 1.
Covering a number of tracks wherever it lands: span. Edge to edge: 1 / -1.
An item in the wrong place: DevTools' grid overlay shows the line numbers, as the debugging corner says.
Your turn
Which columns does grid-column: 1 / 3 cover?Tap to reveal
- Between line 1 and line 3.
Columns 1 and 2.
How many vertical lines does a 5-column grid have?Tap to reveal
- n + 1.
Six.
How do you make an item cover three rows, wherever it lands?Tap to reveal
- A count, not lines.
grid-row: span 3.
Did you know?
-1 is the end of the grid you drew
Line -1 is the last line of the grid you drew, not of every row the browser adds. The Grid standard says line numbers count from the edges of the explicit grid: positive ones from the start, beginning at 1, and negative ones from the end, beginning at -1. Rows the grid makes on its own, past your template, are not counted.
Why it fits here: This topic's 1 / -1 runs from edge to edge of the grid you drew; rows made later lie outside it.
Source: W3C: CSS Grid Layout
Named areas name their lines too
Naming an area also names its lines. For each named area, say main, the Grid standard creates four line names on its own: main-start for its first row line and first column line, and main-end for its last ones. So grid-column: main-start / main-end places an item exactly across the main area.
Why it fits here: It joins this topic's lines to the next topic's named areas.
Source: W3C: CSS Grid Layout
In one line
A grid's lines are numbered from 1, and -1 is the last. Writing grid-column: 2 / 4 places an item between lines 2 and 4, span n covers n tracks wherever it lands, and 1 / -1 runs edge to edge.
A page laid out by name: grid-template-areas
At a glance
An architect's plan labels its rooms instead of measuring them: kitchen, hall, bedroom. The grid-template-areas property, on the container, draws a page the same way, as a small picture of names: one quoted string for each row, and one name for each column.
Then grid-area, on an item, puts it into the area with its name, such as header or sidebar. A name repeated across cells makes a bigger area, and every area must be a rectangle. Reading the strings from top to bottom shows the layout at a glance.
Take a guess: If the name header fills the whole first string, how many columns does the header cover?
An architect's floor plan does not say "room at line 2 to line 4". It labels the rooms: kitchen, hall, bedroom, and the drawing shows where each one goes. Grid can be written the same way: you draw a small picture of the layout in words, and each part takes its place by name.
grid-template-areas, on the container, is a picture of the layout in names: one quoted string per row, one name per column. grid-area, on an item, says which name it fills.
<!DOCTYPE html>
<style>
body { margin: 0; }
.page {
display: grid;
grid-template-columns: 150px 1fr;
grid-template-rows: 50px 100px 30px;
grid-template-areas:
"head head"
"side main"
"foot foot";
width: 600px;
}
header { grid-area: head; }
aside { grid-area: side; }
main { grid-area: main; }
footer { grid-area: foot; }
.page > * { background-color: lightyellow; border: 1px solid gold; }
</style>
<div class="page">
<header>Asha Stores</header>
<aside>Categories</aside>
<main>Products</main>
<footer>Shop 4, MG Road</footer>
</div>
Checked in Chrome
- the header fills the whole first row: 600 by 50
- the second row: a 150px sidebar beside a 450px main area
- and the footer across the bottom, 150 down
Read the picture as if it were the page. "head head" means the header covers both columns of the first row. "side main" puts the sidebar and the main area side by side, and "foot foot" runs the footer across the bottom. A name repeated across a row or down a column makes its area span them.
A memory aid
Draw the page in words. One string per row, one name per column, each area a rectangle of the same name.
Changing the layout without touching the HTML
The picture is only CSS, so a different picture rearranges the page with no change to the HTML. On a narrow phone screen, one column suits better: every part stacked.
<!DOCTYPE html>
<style>
body { margin: 0; }
.page {
display: grid;
grid-template-columns: 150px 1fr;
grid-template-rows: 50px 100px 30px;
grid-template-areas:
"head head"
"side main"
"foot foot";
width: 600px;
}
header { grid-area: head; }
aside { grid-area: side; }
main { grid-area: main; }
footer { grid-area: foot; }
.page > * { background-color: lightyellow; border: 1px solid gold; }
.page.phone {
grid-template-columns: 1fr;
grid-template-rows: auto;
grid-template-areas: "head" "main" "side" "foot";
width: 300px;
}
</style>
<div class="page phone">
<header>Asha Stores</header>
<aside>Categories</aside>
<main>Products</main>
<footer>Shop 4, MG Road</footer>
</div>
Checked in Chrome
- one column: every part the full 300px
- stacked in the picture's order: header, main, then the sidebar, then the footer
Here the main area comes before the sidebar on the phone, though the sidebar comes first in the HTML. Like flexbox's order, this moves things on screen only; keep the HTML in the order that makes sense to read, and move only small things.
The rules of the picture
- every row's string must have the same number of names, one per column;
- each area must be a rectangle: an L shape of one name is not allowed, and the whole template is then ignored;
- a full stop,
., marks an empty cell that no area takes.
Worked example 5
A school's notice page should have a title across the top, and a 200px column of dates on the left beside the notices. Under the notices goes a contact line, and the corner under the dates stays empty. The page is 600px wide. Draw it in names.
What we have: four parts, one empty corner
What we need: grid-template-areas for three rows, and the columns
The plan: two columns, 200px and 1fr; three rows; a full stop for the empty corner
<!DOCTYPE html>
<style>
body { margin: 0; }
.notices {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-rows: 40px 100px 30px;
grid-template-areas:
"title title"
"dates list"
". contact";
width: 600px;
}
h1 { grid-area: title; margin: 0; }
.dates { grid-area: dates; }
.list { grid-area: list; }
.contact { grid-area: contact; }
</style>
<div class="notices">
<h1>Notices</h1>
<div class="dates">15 June</div>
<div class="list">Admissions close</div>
<div class="contact">Office: 020 2567 1234</div>
</div>
Checked in Chrome
- the contact line sits under the notices, at 200 across and 140 down
- the title runs across the whole top
- the dates fill the 200px column
"title title" "dates list" ". contact", with columns 200px 1fr.
Check: the contact line landed exactly under the notices, and the corner under the dates stayed empty.
When you are stuck: grid areas
Write the picture first, one string per row; then give each item its grid-area name.
The whole layout ignored? A row has the wrong number of names, or an area is not a rectangle.
An empty cell: a full stop.
Your turn
What does "head head" in the first row of grid-template-areas do?Tap to reveal
- The same name twice in one row.
The head area covers both columns of that row.
Which character marks an empty cell?Tap to reveal
- A small mark.
A full stop, ..
Can an area be L-shaped?Tap to reveal
- What shape must every area be?
No: every area must be a rectangle.
Did you know?
Only rectangles allowed
A named area must be a rectangle. The Grid standard says that if an area's cells do not form a single filled-in rectangle, the whole grid-template-areas declaration is invalid, so the layout is not used at all. An L-shaped area is not allowed, though the standard notes that other shapes may be permitted in a future version.
Why it fits here: This topic's rule that every area is a rectangle is how the standard itself puts it.
Source: W3C: CSS Grid Layout
A dot is an empty cell
In the picture of names, a full stop means an empty cell. The Grid standard says a run of one or more full stops, such as . or ..., is a null cell token: a cell that belongs to no area. Several dots in a row still make just one cell, so you can use as many as you need to line the picture up.
Why it fits here: It lets this topic's picture of names leave a cell empty.
Source: W3C: CSS Grid Layout
In one line
grid-template-areas draws the layout as a picture of names, one string per row and one name per column; grid-area puts an item in its named area, and every area must be a rectangle.
Grids that arrange themselves
At a glance
A cinema seats however many people come, without a new plan for every show. A grid can work the same way. Rows you did not draw are made when items need them, and grid-auto-rows sets how tall they are.
The pattern repeat(auto-fill, minmax(200px, 1fr)) fits as many columns as the screen holds, auto-fit stretches them to fill the row, and dense fills holes left by bigger items. Together they make a card layout that needs no breakpoints. Flexbox suits one direction, grid two.
Take a guess: If cards need at least 200px and the screen is 650px wide, how many columns does repeat(auto-fill, minmax(200px, 1fr)) make?
A cinema hall seats however many people come: the ushers do not need a new plan for every show. A grid can work the same way: it makes as many rows as its items need, and even as many columns as the screen can hold.
Rows made on demand: grid-auto-rows
Rows that you did not draw are made automatically when items need them. grid-auto-rows sets how tall those automatic rows are.
<!DOCTYPE html>
<style>
body { margin: 0; }
.board {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-auto-rows: 60px;
width: 600px;
}
.board div { background-color: gold; border: 1px solid white; }
</style>
<div class="board">
<div>1</div><div>2</div><div>3</div>
</div>
Checked in Chrome
- only two columns were drawn and no rows; a 60px row was made for the third item
As many columns as fit: auto-fill and minmax()
This is grid's most useful trick. minmax(150px, 1fr) means "at least 150px, and at most one share of the space". Put it in repeat(auto-fill, ...), and the browser makes as many columns as fit, then shares any leftover between them.
<!DOCTYPE html>
<style>
body { margin: 0; }
.shop {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 10px;
width: 600px;
}
.shop div { height: 40px; background-color: lightyellow; }
</style>
<div class="shop">
<div>Rice</div><div>Dal</div><div>Atta</div><div>Oil</div><div>Salt</div>
</div>
Checked in Chrome
- five cards on two rows
- three columns in 600px: the first and fourth cards both start at the left
Work it out: three columns of 150px and two gaps of 10 make 470, which fits in 600; four would make 630, which does not. So three columns, sharing the spare 130 pixels, about 193 each. On a 300px phone screen the same rule makes two columns, and on a wide screen more: one line of CSS, a layout for every screen.
auto-fill or auto-fit
The difference shows when there are fewer items than columns. auto-fill keeps the empty columns, so the items stay their minimum size. auto-fit folds the empty columns away, so the items stretch to fill the row.
<!DOCTYPE html>
<style>
body { margin: 0; }
.grid { display: grid; width: 600px; }
.fill { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); }
.fit { grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); }
.grid div { height: 40px; background-color: gold; }
</style>
<div class="grid fill"><div>A</div><div>B</div></div>
<div class="grid fit"><div>C</div><div>D</div></div>
Checked in Chrome
- auto-fill keeps six 100px columns, so the two items stay 100px
- auto-fit folds the empty columns away, so the two items stretch to 300px each
Filling holes: grid-auto-flow: dense
When a wide item does not fit the end of a row, it moves to the next row and leaves a hole behind. grid-auto-flow: dense lets later, smaller items move back to fill such holes. It changes the visual order, so use it only where order does not matter, such as a gallery of photos.
<!DOCTYPE html>
<style>
body { margin: 0; }
.gallery {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-auto-rows: 40px;
grid-auto-flow: dense;
}
.gallery div { background-color: lightyellow; border: 1px solid gold; }
.wide { grid-column: span 2; }
</style>
<div class="gallery">
<div class="wide">A</div>
<div class="wide">B</div>
<div>C</div>
</div>
Checked in Chrome
- B does not fit beside A, so it goes to row 2; C moves back up to fill the hole in row 1
- C sits at the end of row 1, beside A
Lining items up in their cells, and the grid in its box
place-items: center centres every item inside its own cell, both ways, in one line. And when the tracks are smaller than the container, align-content and justify-content move the whole set of tracks, as in a flex container with wrapped lines.
<!DOCTYPE html>
<style>
body { margin: 0; }
.screen { display: grid; place-items: center; width: 600px; height: 200px; }
.badge { width: 100px; height: 50px; background-color: gold; }
.rows { display: grid; grid-template-columns: repeat(2, 100px); grid-auto-rows: 40px; align-content: center; height: 200px; }
.rows div { background-color: lightyellow; }
</style>
<div class="screen"><div class="badge">Sale</div></div>
<div class="rows"><div>1</div><div>2</div><div>3</div><div>4</div></div>
Checked in Chrome
- place-items: center puts the badge dead centre: 250 across, 75 down
- align-content: center puts the two 40px rows in the middle of 200px, starting 60 down
Grids and flex containers can also be inline, sitting inside a line of text: display: inline-grid and display: inline-flex, like inline-block for their kinds.
Grid or flexbox?
| Use | When | For example |
|---|---|---|
| flexbox | one direction: a row or a column, sizes set by the content | a menu bar, a row of buttons, an icon beside its label |
| grid | two directions at once, or columns that must line up | a page layout, a board of cards, a photo gallery |
| both | a grid for the page, flex inside its parts | a grid page whose header is a flex row |
Worked example 6
A shop's product page should show cards at least 180px wide, as many in a row as the 600px page allows, with 20px gaps, the rows 80px tall. Write the grid, and work out how many cards fit in a row.
What we have: cards of at least 180px, 20px gaps, a 600px page
What we need: the grid rule and the number of columns
The plan: repeat(auto-fill, minmax(180px, 1fr)); count columns until the next would not fit
- Two cards: 180 + 20 + 180 = 380. Three: 380 + 20 + 180 = 580, which fits in 600. Four would need 780.
- So three columns, sharing the spare 20 pixels: about 186.7 each.
<!DOCTYPE html>
<style>
body { margin: 0; }
.shop {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
grid-auto-rows: 80px;
gap: 20px;
width: 600px;
}
.shop div { background-color: lightyellow; }
</style>
<div class="shop"><div>Rice</div><div>Dal</div><div>Atta</div><div>Oil</div><div>Salt</div><div>Tea</div><div>Ghee</div></div>
Checked in Chrome
- three cards on the first row
- seven cards on three rows: 3, 3 and 1
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 20px; grid-auto-rows: 80px; Three cards a row.
Check: the browser put three cards on the first row and seven on three rows.
When you are stuck: self-arranging grids
Cards that should fit any screen: repeat(auto-fill, minmax(min-width, 1fr)).
Too few items stretching too wide, or not stretching: auto-fit stretches them, auto-fill keeps them small.
Holes left by wide items: grid-auto-flow: dense, only where order does not matter.
Your turn
What does minmax(200px, 1fr) mean for a column?Tap to reveal
- A smallest and a largest.
At least 200px, at most one share of the space.
Two items in a 600px grid of repeat(auto-fit, minmax(100px, 1fr)): how wide is each?Tap to reveal
- auto-fit folds the empty columns away.
300px: they stretch to fill the row.
A row of buttons with sizes set by their words: grid or flexbox?Tap to reveal
- One direction, content-sized.
Flexbox.
Did you know?
Filling holes can shuffle the order
Filling holes has a cost. The Grid standard says dense packing fills holes earlier in the grid with smaller items that come up later, and that this may make items appear out of order. Without dense, placement only ever moves forward through the grid and never goes back to fill a hole.
Why it fits here: This topic's dense fills holes; this is its price, items seen out of their order.
Source: W3C: CSS Grid Layout
Subgrid had to wait for Level 2
One grid feature had to wait. A subgrid is a grid inside a grid that takes its rows or columns from its parent, so the contents of separate cards can line up with each other. The first Grid standard deferred subgrid to Level 2, due to lack of implementation and a wish for further discussion; Level 2 now defines it.
Why it fits here: It is the next step after this topic's grids: a grid inside a grid that shares its parent's lines.
In one line
Grids make their own rows (grid-auto-rows), fit as many columns as the screen holds with repeat(auto-fill, minmax()), stretch them with auto-fit, and fill holes with dense; flexbox suits one direction, grid two.
Where it is used
Most page layouts and card boards built today are grids.
| What you learned | Where it is used | A real example |
|---|---|---|
| grid-template-columns with fr | page layouts | a news site's article column beside a sidebar of related stories |
| repeat(auto-fill, minmax()) | card boards that fit any screen | a shopping site's search results, four cards a row on a laptop and two on a phone |
| span | featured items | a photo gallery where one picture covers two cells |
| grid-template-areas | whole-page layouts | a dashboard with a header, a side menu, the main panel and a footer, rearranged for phones |
| 1 / -1 | full-width rows | a banner across every column of a product board |
| place-items: center | centring | a loading spinner in the middle of a panel |
| grid and flex together | almost everywhere | a grid page whose header row is a flex bar of links |
Mistakes and debugging
These are the grid slips everyone makes, each measured in the browser.
1. display: grid with no columns
<!DOCTYPE html>
<style>
body { margin: 0; }
.board { display: grid; width: 600px; }
</style>
<div class="board"><div>1</div><div>2</div><div>3</div></div>
Checked in Chrome
- (the slip: with no columns drawn, there is one column, and every item takes a full row)
The fix: draw the columns: grid-template-columns: repeat(3, 1fr);.
2. Lines counted as columns
<!DOCTYPE html>
<style>
body { margin: 0; }
.board { display: grid; grid-template-columns: repeat(3, 100px); }
.banner { grid-column: 1 / 3; }
</style>
<div class="board"><div class="banner">Meant to cover all 3</div></div>
Checked in Chrome
- (the slip: 1 / 3 runs from line 1 to line 3, which is only two columns)
The fix: grid-column: 1 / 4 for three columns, or 1 / -1 for all of them.
3. % columns beside gaps
<!DOCTYPE html>
<style>
body { margin: 0; }
.board { display: grid; grid-template-columns: 50% 50%; gap: 20px; width: 600px; }
</style>
<div class="board"><div>Left</div><div>Right</div></div>
Checked in Chrome
- (the slip: two halves of 600 plus a 20px gap need 620px, so the grid overflows its box)
The fix: 1fr 1fr: fr shares only what is left after the gap.
4. An area that is not a rectangle
<!DOCTYPE html>
<style>
.page {
display: grid;
grid-template-areas:
"side head"
"side side";
}
</style>
<div class="page"><div>x</div></div>
Checked in Chrome
- (the slip: side makes an L shape, so the browser throws away the whole template)
The fix: make every named area a rectangle, splitting an L into two names.
5. dense or areas that scramble the reading order
Items moved far from their HTML order confuse keyboard and screen reader users, as flexbox's order did. The fix: keep the HTML in reading order; move only small things.
The debugging corner: the grid overlay
In DevTools' Elements panel, a grid container has a small grid badge beside its tag. Click it, and the page draws the grid's lines with their numbers, positive and negative, and the names of its areas. Most "why is this item there?" questions are answered by reading the numbers off the overlay.
Quick card
The lesson on one card.
Every idea of the lesson
<!DOCTYPE html>
<style>
body { margin: 0; }
.page {
display: grid;
grid-template-columns: 150px 1fr;
grid-template-rows: 40px auto 30px;
grid-template-areas: "head head" "side main" "foot foot";
gap: 10px;
width: 600px;
}
header { grid-area: head; }
aside { grid-area: side; }
main { grid-area: main; }
footer { grid-area: foot; }
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
grid-auto-rows: 50px;
gap: 10px;
}
.cards .featured { grid-column: span 2; }
</style>
<div class="page">
<header>Asha Stores</header>
<aside>Categories</aside>
<main>
<div class="cards">
<div class="featured">Diwali sweets</div>
<div>Rice</div><div>Dal</div><div>Atta</div>
</div>
</main>
<footer>Shop 4, MG Road</footer>
</div>
Checked in Chrome
- the page by areas: header across, a 150px sidebar, the main area beside it after a 10px gap
- the cards fill as many 130px columns as the main area holds
- the featured card spans two columns, wider than the others
| Idea | In one line |
|---|---|
display: grid | on the container; columns and rows at once |
grid-template-columns, -rows | one value per track, in px, fr or both |
fr | a share of the space left after fixed tracks and gaps |
repeat(n, track) | a track written n times |
gap | space between tracks, never at the edges |
grid-column: 2 / 4, span 2, 1 / -1 | between lines; cover two tracks; edge to edge |
grid-template-areas, grid-area | the layout as a picture of names; an item's name |
grid-auto-rows | the height of rows the grid makes itself |
repeat(auto-fill, minmax(150px, 1fr)) | as many columns as fit, at least 150px each |
place-items: center | every item centred in its cell |
| grid or flex | two directions or lined-up columns: grid; one row or column: flex |
The story: Every stall in its square
You draw the board as squared paper: four columns of equal share, three rows. Each stall drops into the next square by itself, and the columns line up from top to bottom.
The stage takes two squares side by side, and the gate stretches across the whole bottom row. Then you name the parts of the board, header, stalls, stage, gate, and write the plan out as a little picture of names that the board follows.
The warden lays his paper plan beside the board. They match square for square. "Now that," he says, "is a map."
Reagents gathered: grid, fr, grid-template-columns, span, grid-area, gap.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- HTML Living Standard (WHATWG) (CC BY 4.0: "Copyright WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License" (its acknowledgements page, read 2026-10-26); reused with credit)