← All articles

The Grid Mental Model

Juniper Hale · 1 min read
Share image
Share image

Grid has a reputation for being complicated. The spec is enormous, the syntax looks like ASCII art, and there are about nine ways to do everything. But the core mental model fits on a napkin.

Coloured rectangles arranged on an invisible four-column grid, one spanning two columns
Children are placed into cells; some span more than one.

Flexbox is content-out; Grid is layout-in

Flexbox asks the children how big they'd like to be, then distributes the space. Grid draws the structure first and then drops children into it. That's the whole difference.

layout.css
.wrapper {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.feature {
  grid-column: span 2;
}
1
2
3
4
5
6

The fr unit

1fr means “one share of whatever's left”. It's computed after fixed tracks and gaps, which is why it plays so nicely with gap.

1fr has an implicit minimum of auto, so a long word can blow a track wider than its share. Reach for minmax(0, 1fr) when that happens.

Named areas

.page {
  grid-template-areas:
    'header header'
    'sidebar main'
    'footer footer';
}

It reads like a picture of the layout, because it is one.

0 comments

  • Be the first to comment.