CSS Grid
Flexbox handles one dimension (a row or a column). Grid handles two dimensions (rows and columns) at once. It's the best tool for page layouts, galleries, dashboards and anything that lines up in both directions.
Your first grid
The fr unit means "a fraction of the free space". 1fr 2fr gives the second column twice the width of the first.
grid-template-columns: 200px 1fr; /* fixed sidebar + flexible content */
grid-template-columns: repeat(4, 1fr); /* four equal columns */
grid-template-columns: 1fr minmax(0, 3fr); /* minmax prevents overflow from long content */The magic responsive grid (no media queries)
repeat(auto-fill, minmax(140px, 1fr)) means "fit as many columns as you can, each at least 140px wide, then share out the leftover space." It's probably the most useful single line of CSS there is.
Placing items: spanning rows and columns
Grid lines are numbered from 1. Items can span several tracks:
Named areas: page layout you can read
The layout is drawn as ASCII art in the CSS! On narrow screens, the media query rearranges the areas into a single column.
Alignment
Grid uses the same alignment ideas as flexbox:
| Property | Effect |
|---|---|
justify-items / align-items |
Align every item inside its cell (horizontal / vertical) |
justify-self / align-self |
Align one item |
place-items: center |
Shorthand for both: the shortest way to centre |
justify-content / align-content |
Align the whole grid inside its container |
Flexbox or Grid?
| Use Flexbox when… | Use Grid when… |
|---|---|
| Content decides the size (navbar items, tags) | The layout decides the size (columns, page structure) |
| One direction | Rows and columns together |
| Items should wrap naturally | Items must line up in both directions |
They work great together: a grid page layout with flexbox inside each card.
Practice
Build a dashboard layout: a header across the top; a 4-column row of stat cards that collapses to 2 columns, then 1, on smaller screens (use auto-fit + minmax); and below that, a large chart area spanning 3 columns next to a 1-column activity list.
1.What does grid-template-columns: 1fr 3fr do?
2.Which line creates a responsive grid without media queries?