CSS Grid Summary

CSS Grid arranges items into rows and columns, making it useful for galleries, cards, dashboards, and page sections.

.gallery {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 20px;
}

The element with display: grid becomes the grid container. Its direct children become grid items.

Grid Columns

The grid-template-columns property defines the columns in the grid.

.cards {
	display: grid;
	grid-template-columns: 1fr 1fr 1fr;
}

The fr unit means a fraction of the available space. Three 1fr columns share the space evenly.

Repeat Keeps Columns Shorter To Write

The repeat() function avoids writing the same column size again and again.

.cards {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
}

This creates the same three equal columns as the previous example.

Gap Adds Space Between Grid Items

The gap property adds space between rows and columns without adding outside space around the grid.

.cards {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 24px;
}

Grid And Flex Are Different

Grid is usually best when both rows and columns matter. Flexbox is usually best when items mainly need to line up in one direction.

Interactive Demo

1
2
3
4
5
6

Code Sandbox

AI Tutor