SlashAI

Build a Real Website · Module 2 · CSS: the paint and layout

Flexbox: layout without tears

7 min read · lesson 4 of 5

Before flexbox, centring a box took folklore and prayer. Flexbox lets a parent element arrange its children in a row or column, and it is three lines for most layouts.

nav {
  display: flex;
  justify-content: space-between; /* push apart */
  align-items: center;            /* centre vertically */
  gap: 16px;                      /* space between items */
}

.cards {
  display: flex;
  flex-wrap: wrap;   /* drop to a new row when needed */
  gap: 16px;
}

The three lines that do 80% of layout

  • display: flex — start arranging children.
  • gap — the space between them (no more margin hacks).
  • flex-wrap: wrap — let rows wrap on small screens instead of squashing.

On phones, a flex row with wrap becomes a stacked column automatically when items run out of width. That is responsive design before you have written a media query.

justify-content works along the row, align-items across it. Say that sentence when confused and the right property usually picks itself.

Practice

Lay out your nav with flexbox and make a two-card row that wraps to one column on a phone width.

Previous: Selectors and the box model