Lesson 17 of 52Layout
CSS Grid
Lay out pages and card galleries in rows and columns with grid tracks, fr units, minmax, auto-fit and named template areas.
Flexbox is brilliant at lining things up in one direction: a row of buttons, a column of form fields. But a lot of real layouts are two-dimensional. A photo gallery has rows and columns. A dashboard has a header across the top, a sidebar down the left and a main area that fills the rest. CSS Grid was built for exactly this. You describe the rows and columns once, on the parent, and the children fall into place. It is supported in every modern browser, and it is how most page-level layout is done today.
Turning on grid
Grid works like flexbox in one important way: you style the parent, and the parent arranges its children. Set display: grid on an element and it becomes a grid container. Its direct children become grid items.
On its own, display: grid does very little that you can see. The items stack in a single column, just like normal blocks. The magic starts when you describe the tracks. A track is one row or one column of the grid. You describe columns with grid-template-columns and rows with grid-template-rows, listing one size per track.
.gallery {
display: grid;
grid-template-columns: 200px 200px 200px; /* three columns, 200px each */
gap: 16px; /* space between tracks */
}The gap property puts space between tracks, never around the outside edge. You can set the two directions separately with row-gap and column-gap, or write gap: 24px 12px (rows first, then columns). Gaps are much cleaner than margins on each item, because you never end up with an extra margin on the last one.
Here is a small recipe gallery. Each card is just a div, and the grid puts them in rows of three.
Preview
Try changing 1fr 1fr 1fr to 1fr 2fr 1fr and watch the middle column double. Then try 120px 1fr and see the cards rearrange into two columns, the first one fixed.
Notice the fifth card. You only defined columns, so the grid made a second row by itself. Rows created this way are called implicit tracks. You can control their size with grid-auto-rows: 100px if you want every row the same height.
The fr unit
fr stands for fraction of the free space. The browser first gives fixed tracks (like 200px) their size and takes away the gaps. Whatever is left is shared out between the fr tracks in proportion. With 1fr 2fr 1fr the leftover space is split into four shares: one, two, one.
That is different from percentages. If you write 33% 33% 33% and add a gap, the total is more than 100% and the grid spills out of its box. With 1fr 1fr 1fr the gap is taken out first, so it always fits.
Tracks with a fixed length, like 200px, get exactly that size.
repeat() and minmax()
Typing 1fr twelve times gets old. The repeat() function does it for you: repeat(12, 1fr) makes twelve equal columns, and repeat(3, 100px 1fr) repeats a pattern of two tracks three times.
minmax(min, max) gives a track a range instead of one size. minmax(200px, 1fr) means "never narrower than 200px, but grow to take a fair share of the space". It is the key to grids that adapt.
| You write | You get |
|---|---|
repeat(4, 1fr) | Four equal columns |
200px 1fr | A fixed sidebar and a flexible main area |
minmax(150px, 300px) | One column between 150px and 300px wide |
repeat(auto-fit, minmax(180px, 1fr)) | As many columns as fit, each at least 180px |
grid-template-columns: 200px 1fr 1fr and gap: 20px. How wide is each 1fr column?Responsive cards without media queries
This is the trick that made Grid famous. Combine repeat(), minmax() and the keyword auto-fit:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
gap: 12px;
}Read it in plain words: "make as many columns as will fit, where each column is at least 160px and they share any extra space". On a wide screen you get five columns. On a phone you get one. You did not write a single breakpoint.
The preview below has a resize handle in its bottom right corner. Drag it to make the box narrower and wider, and watch the column count change.
Preview
Now change auto-fit to auto-fill and widen the box as far as it goes. With auto-fill, the browser keeps making empty columns once your four cards run out, so the cards stop growing. With auto-fit, the empty columns collapse to zero and the real cards stretch to fill the row. For a handful of cards, auto-fit is usually what you want.
Placing items on lines
Every grid has numbered grid lines: the edges between tracks. A three-column grid has four vertical lines, numbered 1 to 4 from the left. Negative numbers count from the end, so -1 is always the last line.
You place an item by saying which lines it starts and ends on:
.feature {
grid-column: 1 / -1; /* from the first line to the last: full width */
}
.tall {
grid-row: span 2; /* take up two rows, starting wherever it lands */
}grid-column: 1 / 3 is shorthand for grid-column-start: 1 and grid-column-end: 3, so the item covers columns one and two. span 2 means "two tracks wide" without caring where it starts. Items you do not place are flowed into the next empty cells automatically, left to right, top to bottom.
Preview
Try giving .photo the rule grid-column: span 2; as well, so it becomes a big square. Then add grid-auto-flow: dense; to .board and see the smaller stories fill the hole that appears.
Named areas
Line numbers are precise but hard to read. grid-template-areas lets you draw the layout as text. Each string is one row, and each word is one cell. Repeat a name to make an area span several cells, and use a dot for an empty cell.
.page {
display: grid;
grid-template-columns: 180px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"nav main"
"footer footer";
}
.site-header { grid-area: header; }
.site-nav { grid-area: nav; }
.content { grid-area: main; }
.site-footer { grid-area: footer; }Areas must be rectangles. An L-shaped area is invalid, and the browser ignores the whole grid-template-areas declaration.
Preview
Swap the layout by editing only the strings. Change the middle row to "main nav" to move the sidebar to the right. Or try a one-column phone layout: set grid-template-columns: 1fr and the areas to "header" "nav" "main" "footer". The HTML never changes, which keeps the reading order sensible for screen readers.
Match each property to its job.
Grid or Flexbox?
They are not rivals. Most real pages use both.
- Use Flexbox when the content decides the layout and you think in one line: a nav bar, a row of tags that wraps, a button with an icon. Items size themselves and flex shares what is left.
- Use Grid when the layout decides where content goes and you think in rows and columns at once: a page shell, a card gallery where every column must line up, a form with labels in one column and inputs in another.
A quick test: if you want items in different rows to line up with each other, use Grid. Flex rows are independent, so the third card in row one has no idea where the third card in row two is.
A common pattern is Grid for the page and the gallery, and Flexbox inside each card to push the button to the bottom. One more feature worth knowing: grid-template-columns: subgrid lets a nested grid reuse its parent's tracks, so the titles of cards side by side line up. It works in all modern browsers; check Can I Use if you need to support older ones.
None picked yet
- grid container
- An element with display: grid. It defines the tracks and arranges its direct children.
- track
- One row or one column of a grid.
- fr
- A fraction of the free space left after fixed tracks and gaps are taken out.
- minmax()
- Gives a track a minimum and maximum size, like minmax(200px, 1fr).
- auto-fit
- Inside repeat(), makes as many columns as fit and collapses empty ones so items stretch.
- grid line
- A numbered edge between tracks, used to place items (1 is the first, -1 the last).
- grid-template-areas
- A property that draws the layout as named cells in strings.