CSS Grid
🏠The everyday picture
A chessboard or a newspaper front page: rows and columns, where a big story can span three columns and a small one takes one box.
📘What it really is
- Grid arranges children in two directions at once, rows and columns:
.gallery {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 1rem;
}
fr means "a fraction of the free space", so three 1fr columns are equal.
repeat(3, 1fr)is a shorter way to write1fr 1fr 1fr.- A powerful pattern that fits as many columns as there's room for, with no extra rules:
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
- Items can span:
grid-column: span 2;makes one item two columns wide. - Grid or Flexbox?
- Flexbox: one line of things (a menu, a row of buttons), where content decides the sizes;
- Grid: a two-dimensional layout (a gallery, a page with sidebar), where the layout decides the sizes.
- They're often used together: a grid of cards, each card using Flexbox inside.
🖱️Try it
Change your .cards section to use Grid with repeat(auto-fit, minmax(220px, 1fr)) instead of Flexbox. Resize
the window: the columns change from three to two to one automatically. Inspect the section: developer tools
show a grid badge that draws the grid lines when clicked.
✅Quick check
A photo gallery in rows and columns: Flexbox or Grid?
Show the answer
Grid, because it's a layout in two directions.
What does 1fr mean?
Show the answer
One share of the free space. Columns of 1fr 2fr split the space one-third and two-thirds.
