Where flexbox arranges items along one direction, CSS Grid is two-dimensional — it defines rows and columns at the same time, and places items anywhere in that grid.
.container {
display: grid;
}Defines the number and size of columns and rows.
.container {
display: grid;
grid-template-columns: 200px 200px 200px;
grid-template-rows: 100px 100px;
}fr represents a fraction of the available space — much more flexible than fixed pixel widths.
.container {
grid-template-columns: 1fr 2fr 1fr; /* middle column is twice as wide */
}repeat() avoids typing the same value over and over. minmax() gives a track a minimum and maximum size.
.container {
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}.container {
display: grid;
gap: 16px; /* row and column gap */
gap: 16px 24px; /* row gap, column gap */
}An item can span multiple columns or rows by specifying start and end lines.
.item-featured {
grid-column: 1 / 3; /* starts at line 1, ends at line 3 — spans 2 columns */
grid-row: 1 / 3;
}Named areas make a layout's structure readable at a glance.
.container {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-areas:
"sidebar header"
"sidebar content";
}
.sidebar { grid-area: sidebar; }
.header { grid-area: header; }
.content { grid-area: content; }| Grid vs. Flexbox | Use when |
|---|---|
| Grid | The layout needs rows and columns together — a page shell, a card gallery, a form grid |
| Flexbox | Items flow in one direction and need to distribute or align along it — a navbar, a button group |
Practice it interactively
This site's Grid Generator tool (under Tools) builds a grid visually and outputs the CSS — a good way to see grid-template-areas take shape without writing it by hand first.