Grid

Place grid items

Position and span items using numbered or named grid lines while preserving a sensible source order for automatic placement.

Auto-placement fills the grid in source order, and most of the time that’s what you want. When one item needs a specific spot, or needs to span more than one cell, you place it yourself.

Placement works with grid lines. To stretch a featured card across the first two columns in the first row:

.featured {
  grid-column: 1 / 3;
  grid-row: 1;
}

grid-column: 1 / 3 means “start at line 1, end at line 3”. That covers two column tracks. Remember that lines start at 1, not 0, and a three-column grid has four lines.

If you don’t care where the item starts, just say how many tracks it should cover:

.featured {
  grid-column: span 2;
}

Auto-placement picks the start, and the item takes two columns from there.

Counting from the end

Negative numbers count backward from the last line. -1 is always the last explicit line. So grid-column: 1 / -1 spans every column, no matter how many there are. I use this for full-width headers and footers inside a grid because it keeps working when I add a column later.

Named lines

Numbers get hard to read in a big layout. You can name the lines where you define the tracks:

.layout {
  grid-template-columns:
    [sidebar-start] minmax(12rem, 1fr)
    [content-start] minmax(0, 3fr) [content-end];
}

Then grid-column: content-start / content-end says what it means. Six months later you’ll thank yourself.

Placement changes pixels, not the DOM

Everything you place still keeps its position in the HTML. Screen readers read the source order. The Tab key follows the source order. If you move the newsletter box to the top visually, keyboard users still reach it last.

So keep the HTML in the order that makes sense when read aloud, and use placement for the visual arrangement only. If the two disagree badly, fix the HTML.

The same caution applies to grid-auto-flow: dense. It lets Grid backfill holes with later items, which can make the visual order jump around. Fine for a photo mosaic, bad for a form.

Overlapping on purpose

Two items placed in the same cell overlap. Grid allows this and it’s handy for a caption over an image. Watch the contrast of text over the image, and make sure one interactive element doesn’t cover another one that users need to click.

Try it on the feature grid: turn on line numbers in DevTools, then place one card with numbers, one with span, and one with named lines. Tab through the page afterwards and compare the keyboard order with what you see.

Lesson completed