CSS Grid
CSS Grid lays out items in two dimensions at once — rows and columns. You define the tracks on the container, and items fall into place or are placed exactly where you want. It's the most powerful layout tool in CSS, ideal for page layouts, galleries and dashboards.
Defining columns
grid-template-columns lists each column's size. Items fill the cells in order, creating new rows automatically. gap sets the space between rows and columns.
The fr unit
fr means "a fraction of the remaining space". After fixed-size tracks and gaps are taken out, the rest is divided by the fr values — no percentage arithmetic needed.
repeat() and minmax()
repeat(4, 1fr) saves writing 1fr 1fr 1fr 1fr. minmax(min, max) sets a size range for a track — here, at least 60px and at most an equal share.
Responsive grids without media queries
This one line is the most useful grid recipe: auto-fill creates as many 150px-or-wider columns as fit, and 1fr stretches them to fill the row. Resize the window and the number of columns adapts automatically. (auto-fit is similar, but collapses empty tracks so a few items stretch across the whole row.)
Rows
grid-template-rows sizes the rows you define; grid-auto-rows sizes any extra rows created automatically. Rows usually stay auto so they fit their content.
Spanning cells
Alignment
| Property | Aligns |
|---|---|
justify-items / align-items | Items inside their cells (horizontally / vertically) |
justify-content / align-content | The whole grid within the container, when tracks don't fill it |
justify-self / align-self | One item within its cell |
place-items, place-content, place-self | Shorthands for both directions |
Grid or flexbox?
| Use Grid when… | Use Flexbox when… |
|---|---|
| You want rows and columns to line up (two dimensions) | You're laying out items in a single row or column |
| The layout defines the sizes | The content defines the sizes |
| Page layouts, card grids, forms with aligned labels | Navbars, toolbars, button groups, centring one thing |
They work together: a grid page layout often contains flex components.