Grid

Start a Grid layout

Turn a parent into a grid container and distinguish explicit tracks, grid lines, cells, areas, and automatically placed items.

Grid is the layout tool for two dimensions. Where Flexbox thinks in one line at a time, Grid thinks in rows and columns at once. Items in different rows share the same columns, so everything lines up.

You turn it on like Flexbox, with one declaration on the parent. Three equal columns for the feature cards:

.features {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 1rem;
}

.features becomes the grid container and its direct children become grid items. grid-template-columns defines three tracks, which is the Grid word for a column or a row.

The vocabulary

A few terms come up in every Grid discussion, so let’s fix them now.

Three column tracks are surrounded by four grid lines, numbered 1 to 4 from the start. Lines are what you place items against.

A cell is where a row track and a column track cross, the smallest unit. An area is a rectangle made of one or more cells.

The rows and columns you write in your CSS are the explicit grid. When you have more items than cells, Grid adds rows on its own. Those are the implicit grid.

Auto-placement

You didn’t tell any card where to go, yet they filled the grid. That’s auto-placement. Grid walks the items in source order and drops each into the next free cell, left to right, then the next row.

Add a fourth card and it lands in a new implicit row, in the first column. You never wrote that row. Grid created it because the content needed it.

What fr means

fr is a fraction of the leftover space. The browser first takes out the gaps and any fixed tracks, then splits what’s left according to the fractions. 1fr 1fr 1fr is three equal shares.

One thing can break the equality. A track never gets narrower than its content’s minimum, so a card with a long unbreakable URL forces its column wider than its siblings. We’ll fix that in the next lesson.

Grid only manages its children

Grid controls the direct children, nothing deeper. A heading inside a card is laid out by the card in normal flow, not by the grid. If you want the card’s insides on a grid too, give the card its own display: grid.

Open the course page, apply the three-column rule to .features, and turn on the Grid overlay in DevTools. Enable line numbers and track sizes. Then add a fourth card in the HTML and watch the implicit row appear. Seeing the lines, the gaps, and the placement order once makes the rest of the module click.

Lesson completed