Course outline · 0% complete

0/30 lessons0%

Course overview →

CSS grid basics

lesson 7-1 · ~9 min · 21/30

Quiz

Warm-up from lesson 6-1: justify-content aligns flex items along which axis?

Grid: rows AND columns at once

Look at any app you use daily — a photo gallery, a dashboard of stat cards, a page with a sidebar — and you are looking at rows and columns that stay aligned with each other. Flexbox lays items out along one axis, so aligning across rows meant hacks. Grid controls two:

.gallery {
  display: grid;
  grid-template-columns: 200px 1fr 1fr;
  gap: 16px;
}
  • grid-template-columns defines the column tracks: here a fixed 200px column, then two flexible ones.
  • fr is a new unit: one fraction of the free space. 1fr 1fr splits the leftover equally, and 2fr 1fr would split it 2 to 1, just like flex-grow in lesson 6-2.
  • Children fill the cells automatically, left to right, wrapping into new rows as needed.

The shorthand you will type constantly: grid-template-columns: repeat(3, 1fr); makes three equal columns.

200px1fr1frfixedflexibleflexiblecellcellcell
grid-template-columns: 200px 1fr 1fr. The first track is fixed, and the two gold fr tracks share whatever space remains.

Spanning and placing

Any grid child can claim more than one cell:

.featured {
  grid-column: 1 / 3; /* start at line 1, end at line 3: spans 2 columns */
}
.sidebar {
  grid-row: 1 / 4;    /* spans 3 rows */
}

Grid counts the lines between tracks, starting at 1, so three columns have four lines. grid-column: 1 / 3 reads as start at line 1, end at line 3.

When to reach for which tool: grid for the page-level skeleton (header, sidebar, content, galleries) and flexbox for one-dimensional rows inside it (navbars, button groups, card innards). They compose: a grid cell often contains a flex container, like your lesson 6-3 header.

Quiz

A grid has grid-template-columns: 1fr 2fr and 300px of free space. How wide is the second column?

Turn the six photos into a gallery. In the CSS pane give .gallery three declarations: display: grid, grid-template-columns: repeat(3, 1fr), and gap: 12px. Then make the first tile featured: add a .featured rule with grid-column: 1 / 3 so it spans two columns.

Problem

Which CSS unit means one share of a grid's free space?