Sub topic 13
Building Grids with CSS Grid
This chapter turns the grid you designed on paper into working CSS. It assumes you know the parts of a grid (margins, columns, gutters, rows, modules), the column and module arithmetic from earlier chapters, and basic HTML and CSS selectors. It does not assume you have used CSS Grid before.
Mapping grid parts to CSS
CSS Grid has a property for each part of a design grid. Once you know the mapping, a grid spec from a layout tool translates almost line by line.
| Design term | CSS Grid equivalent |
|---|---|
| Page margin | `padding-inline` on a wrapper, or `margin-inline: auto` with `max-width` |
| Column | A track defined in `grid-template-columns` |
| Gutter | `column-gap` (or `gap` for both directions) |
| Row height, module height | `grid-template-rows` |
| Module | One cell where a column track and a row track cross |
| Flowline or column edge | A numbered grid line |
| Spanning a column or module group | `grid-column` and `grid-row` with `span` |
Grid lines are the idea to understand first. A grid with 12 columns has 13 vertical lines, numbered 1 to 13. Gutters sit between the lines of adjacent columns and are subtracted by gap. When you write grid-column: 9 / span 4, you start at line 9 and cover four columns, ending at line 13.
A multi-column grid
Start with a 12-column grid, a common choice because 12 divides evenly into 2, 3, 4 and 6 columns.
.columns {
display: grid;
grid-template-columns: repeat(12, 1fr);
column-gap: 1.5rem;
max-width: 72rem;
margin-inline: auto;
}
.article { grid-column: 1 / span 8; }
.sidebar { grid-column: 9 / span 4; }You can check this against the grid math. At a 16 px root size, 72rem is 1152 px and the gutter is 24 px. Eleven gutters take 264 px, so each column is (1152 − 264) / 12 = 74 px. The article spans eight columns and seven gutters: 8 × 74 + 7 × 24 = 760 px. Browser developer tools can draw grid lines over the page, so you can compare these numbers with what the browser actually computed.
The same arithmetic works in code. This is the function from the grid math chapter:
def column_width(page_width, margin, gutter, columns):
"""Width of one column when both side margins are equal."""
usable = page_width - 2 * margin
return (usable - (columns - 1) * gutter) / columns
# A4 portrait is 210 mm wide: 20 mm margins, 5 mm gutters, 4 columns
print(column_width(210, 20, 5, 4)) # 38.75CSS does this calculation for you. 1fr means one share of the free space left after gutters and fixed tracks are removed.
Outer margins on screens
Print margins are fixed measurements. On screen the viewport width varies, so you need two rules: a minimum margin on narrow screens and a maximum content width on wide ones.
.page {
padding-inline: clamp(1rem, 5vw, 2.5rem);
}
.columns {
display: grid;
grid-template-columns: repeat(12, 1fr);
column-gap: 1.5rem;
max-width: 72rem;
margin-inline: auto;
}Put .columns inside .page. The padding keeps text away from the screen edge on phones. Above 72 rem the grid stops growing and margin-inline: auto centers it, which keeps the measure (line length) under control on large monitors.
A modular grid
A modular grid adds fixed-height rows to the columns, so every cell is a module. Items then snap to blocks in both directions.
.modular {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(6, 8rem);
gap: 1rem;
}
.feature { grid-column: 1 / span 2; grid-row: 1 / span 3; }
.caption { grid-column: 3 / span 2; grid-row: 1; }The feature image covers a block of 2 × 3 modules. The caption sits beside it in the top row. Because both placements are explicit, their position does not depend on source order.
Two details matter here:
- A spanning item includes the gutters inside its span. The feature is 2 columns wide plus one gutter, and 3 rows tall plus two gutters.
- Rows in
grid-template-rowsare only the explicit rows. If you place more items than fit, the browser creates implicit rows, and their height comes fromgrid-auto-rows. Setgrid-auto-rows: 8remso extra rows match your modules.
Responsive grids
A responsive grid changes the number of columns at breakpoints. Mobile-first CSS declares the smallest layout first and widens it with min-width queries.
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1rem;
}
@media (min-width: 48em) {
.grid { grid-template-columns: repeat(8, 1fr); }
}
@media (min-width: 64em) {
.grid { grid-template-columns: repeat(12, 1fr); gap: 1.5rem; }
}The 4, 8 and 12 column counts nest well, so a half-width item is 2, 4 or 6 columns wide depending on the breakpoint. The breakpoints use em units, which respect the reader's font-size setting.
Reset spans on narrow screens
A common bug appears when you combine the 12-column placement above with this responsive grid. On a 4-column grid, grid-column: 1 / span 8 asks for eight columns, so the browser adds implicit columns and the page scrolls sideways. Give items a full-width default and apply spans only inside the breakpoint that has enough columns:
.article,
.sidebar {
grid-column: 1 / -1;
}
@media (min-width: 64em) {
.article { grid-column: 1 / span 8; }
.sidebar { grid-column: 9 / span 4; }
}The line number -1 is the last line of the explicit grid, so 1 / -1 fills the full width at any column count. Use it for full-bleed items too.
Fluid grids without breakpoints
When the content is a set of equal cards, you can let the browser choose the column count:
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 16rem), 1fr));
gap: 1rem;
}Each column is at least 16 rem wide and the browser fits as many as it can. min(100%, 16rem) prevents overflow on screens narrower than 16 rem. The trade-off is that the column count is a result, not a decision. You lose the 4-8-12 system, so items cannot reliably span "half the grid". Use fluid auto-fill for uniform collections and a defined column count for editorial layouts.
Vertical rhythm
CSS has no real baseline grid. You can approximate one by making line height and block spacing multiples of one unit.
body {
font-size: 1rem;
line-height: 1.5rem;
}
p, h2, figure {
margin-block: 0 1.5rem;
}Text then falls on lines 1.5 rem apart across all columns. The approximation breaks when an element has an uneven height, such as an image with an arbitrary aspect ratio, or a heading with a larger font size and a line height that is not a multiple of 1.5 rem. Give larger headings a line height of 3 rem, or set image block sizes to multiples of the unit. Row heights in a modular grid should also be multiples of the unit (8 rem is 5⅓ units, so 7.5 rem or 9 rem fits the rhythm better).
Common errors
- Columns wider than expected.
1fris shorthand forminmax(auto, 1fr), so a long unbreakable word, a wide table or an image can force a track wider than its share. Userepeat(12, minmax(0, 1fr))when the content is unpredictable. - Items out of order. Without explicit placement, items fill cells in source order. Mixed explicit and automatic placement can leave gaps. Place every item on a grid you want to control precisely, or set
grid-auto-flow: denseonly when reordering is acceptable, because it can detach visual order from reading order. - Gutters doubled. Do not add margins to items inside a grid that already has
gap. The two stack. - Nested grids that drift. A grid inside a grid item has its own tracks. Use
grid-template-columns: subgridon the inner container to share the parent's column lines. Check your target browsers' support first. - Hidden reading-order problems. Screen readers and the Tab key follow source order, not visual position. Write the HTML in logical order and use placement only to arrange it.
Exercise
A page uses max-width: 60rem, column-gap: 1rem and grid-template-columns: repeat(6, 1fr), with a 16 px root size. How wide in pixels is one column, and what grid-column value places an item across the middle four columns?
Show answer
60 rem is 960 px. Five gutters take 80 px, leaving 880 px, so each column is 880 / 6 ≈ 146.67 px. The middle four columns start at line 2 and end at line 6, so use grid-column: 2 / span 4 (or 2 / 6).
Exercise
On a 4-column mobile grid, an item has grid-column: 1 / span 8 and the page scrolls sideways. Why does this happen, and how do you fix it without changing the desktop layout?
Show answer
The span asks for eight columns on a grid that has four, so the browser creates four implicit columns outside the container width. Set the item's default to grid-column: 1 / -1 and move the 1 / span 8 rule into a min-width media query where the grid has at least eight columns.