CSS Grid Fundamentals
15 minBeginnerHTML · CSS · JS
In this lesson
- ▸Create a grid with
display: gridandgrid-template-columns - ▸Share space fairly with the
frunit andrepeat() - ▸Space rows and columns with
gap - ▸Make an item span several columns with
grid-column
The big idea
Flexbox lines things up in one direction. Grid lays things out in rows and columns at the same time — perfect for galleries, card lists and page layouts.
Think of a grid like the lines in an exercise book. You draw the columns on the parent, and the children drop into the cells one by one, left to right, then onto the next row.
.cards {
display: grid;
grid-template-columns: 200px 200px 200px; /* three columns */
gap: 16px; /* space between cells */
}You never said how many rows there are. Grid creates as many as it needs: six cards in three columns makes two rows automatically.
The fr unit: fair shares
Fixed pixel columns don't fit every screen. The fr unit means a fraction of the free space. 1fr 1fr 1fr gives three equal columns that stretch with the page. 2fr 1fr makes the first column twice as wide as the second.
Repeating yourself
grid-template-columns: 1fr 1fr 1fr 1fr;Same thing with repeat()
grid-template-columns: repeat(4, 1fr);repeat(count, size) is just a shortcut. Both lines make four equal columns.
Placing items
By default every item takes one cell. To make one item bigger, tell it how many columns to span:
.featured {
grid-column: span 2; /* take up two columns */
}
.banner {
grid-column: 1 / -1; /* from the first line to the last: full width */
}Lines, not cells
Grid numbers the lines between columns, starting at 1. Three columns have four lines, so 1 / 4 and 1 / -1 both mean "from the very left to the very right". -1 always means the last line.
Grid or flexbox?
Use flexbox for a single row or column of things (a nav bar, a row of buttons). Use grid when you care about rows and columns lining up (a gallery, a dashboard, a whole page). Real sites use both, often nested.
The kuih cards are stacked in one long column. Turn .cards into a grid with three equal columns that stretch with the page — use the fr unit (with or without repeat()).
Checks
- .cards is a grid container
- The grid has three equal columns
- Cards sit side by side and wrap onto a new row
Check understanding
What you learned
- ✓
display: grid+grid-template-columnson the parent creates columns; rows are made automatically. - ✓
frshares the free space;repeat(3, 1fr)gives three equal columns. - ✓
gapspaces rows and columns without any margins. - ✓
grid-column: span 2makes an item cover two columns;1 / -1makes it full width.
Console output from your code appears here.