Flexbox arranges things in one direction — a row or a column. CSS Grid works in two directions at once: rows and columns together. It's how you build real page layouts — galleries, dashboards, card grids — with remarkably little code. Flexbox and Grid are partners, not rivals: reach for Grid when you're laying out in two dimensions.
1Columns, gaps and the fr unit
Turn an element into a grid, then describe its columns with grid-template-columns:
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* three equal columns */
gap: 12px;
}The star here is the fr unit — a "fraction" of the free space. 1fr 1fr 1fr means three equal columns; 2fr 1fr means the first column is twice as wide as the second. No percentages, no maths.
And repeat() saves typing: grid-template-columns: repeat(3, 1fr) is the same as 1fr 1fr 1fr. The gap property adds even gutters between every cell.
display: grid+grid-template-columnsdefines the columns.- The
frunit splits free space into fractions —1fr 1fr= two equal columns. repeat(3, 1fr)is shorthand;gapadds even gutters between cells.
2Spanning cells and responsive grids
An item can span several columns with grid-column:
.feature {
grid-column: span 2; /* take up two columns */
}A grid that responds on its own
Here's a small piece of magic. This one line builds a grid that automatically fits as many columns as will comfortably fit, then wraps — no media queries needed:
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
It reads: "make as many columns as fit, each at least 200px wide, sharing space equally." On a wide screen you get four columns; on a phone, one — automatically. It's a favourite for card galleries.
grid-column: span 2makes an item stretch across multiple columns.repeat(auto-fit, minmax(200px, 1fr))builds a responsive grid with no media queries.- Use Grid for 2-D page layouts and Flexbox for aligning within components — together they cover everything.
3Play with the grid — live
Drag the sliders below to change the number of columns, the item count and the gap, and watch the grid rebuild instantly. Notice how items flow into the columns and wrap onto new rows on their own.
- More columns means items share the row; extra items wrap to new rows automatically.
gapadds even spacing between every cell.- The CSS readout is exactly what produces the grid you see.
★ Practical: a responsive gallery
In any playground:
- Make a grid of six boxes with
repeat(3, 1fr)and agap. - Make one box span two columns with
grid-column: span 2. - Switch the columns to
repeat(auto-fit, minmax(150px, 1fr)). - Narrow the preview and confirm the grid reflows on its own.
Ready to test yourself?
Take the short quiz. Score 60% or more to mark this lesson complete.
Start the quiz →💡 Log in to save your progress and earn the certificate.