Intermediate · CSS layout and responsive design · topic 25 of 64 · 30 min
CSS Grid
Explanation
Rows and columns together
Flexbox handles one direction. Grid handles two: rows and columns. Use flexbox for a line of things (a toolbar), and grid for a whole area (a page layout or a gallery).
Defining columns
.gallery {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* three equal columns */
gap: 16px;
}
/* same thing, shorter */
.gallery { grid-template-columns: repeat(3, 1fr); }The fr unit divides the free space into shares. 2fr 1fr gives the first column two shares and the second one share. You can mix units: 250px 1fr makes a fixed sidebar and a flexible main area.
The magic responsive line
.products {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}minmax(200px, 1fr) means "at least 200px, at most one share". auto-fit creates as many columns as fit in the row. On a phone you get one or two columns, on a laptop four or five, with no media queries at all.
Spanning and areas
.featured { grid-column: span 2; } /* this card is two columns wide */
.page {
display: grid;
grid-template-columns: 220px 1fr;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
header { grid-area: header; }
aside { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }Grid or flexbox?
| Situation | Choose |
|---|---|
| A row of buttons or links | Flexbox |
| Items whose size depends on their content | Flexbox |
| A gallery or card grid that must line up | Grid |
| A whole page with header, sidebar and footer | Grid |
Watch the lesson
CSS Grid · 1/6
Grid lays out rows and columns at the same time.
Prefer a video by a teacher? Find free videos on “css grid layout tutorial auto-fit minmax” on YouTube ↗
In real life: A product grid on a shopping site
A clothing store lists hundreds of products. With repeat(auto-fit, minmax(160px, 1fr)) the grid shows two cards per row on a budget phone, three on a tablet and five on a laptop. A sale banner card uses grid-column: span 2 to stand out, and every card lines up perfectly.
Practice (0/2 done)
Make .products a grid with three equal columns (repeat(3, 1fr)) and a gap of 16px.
Make .gallery a responsive grid that fits as many columns as possible, each at least 180px: grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)). Also make .gallery .wide span 2 columns.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.