Grid
Grid lays things out in two directions at once ~ rows and columns. Where Flexbox is for a row of things, Grid is for a page.
Defining columns
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 8px;
}
fr is a fraction of the leftover space. Three 1frs make three equal columns. 200px 1fr makes a fixed sidebar and a flexible main area.
repeat(3, 1fr) is shorthand for 1fr 1fr 1fr.
The one line worth memorising
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
“Fit as many columns as will fit, each at least 120px wide, sharing the space equally.”
That’s a responsive grid ~ three across on a laptop, one on a phone ~ with no media queries at all. I use it constantly.
Spanning cells
grid-column: span 2 makes an item two columns wide. grid-row: span 2 makes it two rows tall. These are the rare Grid properties that go on the children rather than the container.
Grid or Flexbox?
Two directions at once: Grid. One direction: Flexbox. And they nest happily ~ a Grid page layout with Flexbox rows inside each cell is completely normal.
Click to resume
Use the console below.