Tutorial

CSS Flexbox and Grid, Side by Side

Tutorial · Web Development

Cover: CSS Flexbox and Grid, Side by Side

Flexbox and Grid solve overlapping problems, which is why people keep asking which one to learn. The honest answer: both, because they're built for different shapes of layout.

Flexbox: one dimension at a time

Flexbox lays elements out along a single axis — a row or a column — and excels at distributing space between items in that one direction.

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

justify-content controls spacing along the main axis, align-items controls alignment on the cross axis. A navbar with a logo on the left and links on the right is a two-line solution with Flexbox.

Grid: two dimensions at once

Grid defines rows and columns simultaneously, and lets you place items into specific cells — something Flexbox structurally cannot do on its own.

.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

repeat(3, 1fr) creates three equal-width columns; gap replaces the old margin-hacking approach to spacing between cells.

A card grid that wraps itself

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
}

auto-fit with minmax is the pattern worth memorizing: it fits as many 240px-minimum columns as will comfortably fit, and reflows automatically at any screen width — no media query required.

Rule of thumb: if you're arranging items in a single row or column (a navbar, a button group, a sidebar's content), use Flexbox. If you're laying out a whole page or a genuine grid of cards, use Grid. They also combine — a Grid layout with Flexbox inside each cell is common and perfectly fine.

Centering, solved for good

.center {
  display: flex;
  justify-content: center;
  align-items: center;
}

Two lines, works for text or a whole child element, no table hacks or negative margins. This one snippet alone is worth learning Flexbox for.

Comments