Lessons · HTML and CSS · grid
Grid
display: grid with grid-template-columns lays out children in columns and rows. fr shares free space; repeat(3, 1fr) is three equal columns; extra children wrap to new rows.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Card layouts, galleries, dashboards, the page frame itself: anything two-dimensional is grid, and it replaces the float hacks of the past with one line.
How to think about it
Decide the columns, write them once on the container, and let the rows happen. Reach for flex for a single row; grid when both directions matter.
Worked example
<div class="cards"><div>1</div><div>2</div><div>3</div><div>4</div></div>Four cards in a container.
.cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }Three equal columns with a gap. The fourth card wraps to a new row on its own..cards div { padding: 20px; background: rgb(230, 230, 230); }Boxes you can see.Your turn
Make two equal columns.
.cols { display: grid; grid-template-columns: repeat(2, ); }Write a page and watch it render
The trap
Fixed pixel columns that add up to more than a phone's width. Use fr, or minmax with auto-fill, so the columns follow the space.