CSS Grid is a layout system for two dimensions at the same time: rows and columns. Where flexbox lays things out along one line, grid lets you define a whole table-like structure and place items into it.
Container and items
As with flexbox, there are two roles. The parent is the grid container (display: grid). Its direct children are grid items.
<style>
.grid > div { background: #d0e8f2; border: 1px solid #1a5276; padding: 10px; }
.grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; }
</style>
<div class="grid"><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div></div>
grid-template-columns: 1fr 1fr 1fr defines three equal columns. Six children flow into them automatically, filling two rows. You did not define rows. The browser creates them as needed.
A first vocabulary
| Term | Meaning |
|---|---|
| Track | A single row or column |
| Cell | One square where a row and column meet |
| Area | A rectangle made of one or more cells |
| Line | The dividers between tracks, numbered from 1 |
| Gap | The space between tracks |
Grid or flexbox?
- Use flexbox when you are lining things up in one row or column and the content should decide the sizes (a navbar, a button group).
- Use grid when you want a layout where the structure decides the sizes (a page layout, a card grid, a dashboard).
They work together. A grid for the page, flexbox inside each card.
Browser support
Grid works in every modern browser and has for years. You can use it without fallbacks.
Next, define the tracks: Grid Template Columns and Rows.