DevConnectDevConnect
Sign up · Log in

Layout with flexbox and grid

Which of the two to reach for, and the properties that do the work.

15 min read

Almost every layout on the web is one of these two, and choosing wrongly makes the rest of the work harder than it needs to be.

The distinction. Flexbox lays out along one axis and lets the content decide the sizes. Grid lays out along two axes and lets the container decide them. A row of buttons, a navigation bar, a card footer: flexbox. A page skeleton, a photo gallery, a form with aligned labels: grid.

Flexbox, the four properties that matter. flex-direction sets the main axis. justify-content distributes along it, align-items across it. gap is the spacing, and it replaced the margin tricks that came before it. flex: 1 on a child means "take the remaining space"; flex-shrink: 0 means "never get smaller than your content", which is what stops an icon from being squashed next to a long label.

Grid, the two you need first. grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)) produces a responsive card layout with no media queries at all: as many columns as fit, each at least 16rem, sharing the space equally. grid-column: span 2 makes one item wider than the rest.

Minimum size is the trap. A grid or flex item will not shrink below the size of its content by default, so one long unbroken string pushes the whole layout wider than the screen. min-width: 0 on the item releases that, and it is the fix for most cases of unexplained horizontal scrolling.

Where each one breaks down. Flexbox cannot align items across separate rows; that is what grid is for. Grid cannot let content decide the track sizes as naturally as flexbox does. Nesting one inside the other is normal and not a sign that something has gone wrong.

Go deeper

Lessons are not assessed. Progress towards the certificate is recorded from the work you submit. See all requirements