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

Try it yourself
Result

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

Try it yourself
Result

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()

Try it yourself
Result

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

Try it yourself
Result

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

Try it yourself
Result

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

Try it yourself
Result

Alignment

Try it yourself
Result
PropertyAligns
justify-items / align-itemsItems inside their cells (horizontally / vertically)
justify-content / align-contentThe whole grid within the container, when tracks don't fill it
justify-self / align-selfOne item within its cell
place-items, place-content, place-selfShorthands 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 sizesThe content defines the sizes
Page layouts, card grids, forms with aligned labelsNavbars, toolbars, button groups, centring one thing

They work together: a grid page layout often contains flex components.

Try it yourself

Try it yourself
Result