9: Flexbox

Flexbox is the reason we stopped fighting with floats. It lays elements out along a single axis, with full control over direction, spacing, and alignment.

Flex in 30 seconds

display: flex on a parent makes its children flex items, laid out along a main axis (row or column).

flex:1
flex:1
flex:1
.parent { display: flex; gap: 8px; }
.child  { flex: 1; } /* grow equally */

The big four: direction, justify, align, gap

flex-direction

row (default)

ABC

column

ABC
.row { display: flex; flex-direction: row; }
.col { display: flex; flex-direction: column; }

justify-content: the main axis

space-between

ABC

center

ABC
/* main axis (row = horizontal) */
.row { justify-content: space-between; } /* or center, flex-start, flex-end */

align-items: the cross axis

short tall short

align-items: center centers children vertically within the row.

.row { align-items: center; } /* cross axis: row = vertical */

gap: replaces margins

gap 16pxgap 16px
.parent { gap: 16px; } /* cleaner than margins on children */

Wrapping and growing

flex-wrap

nowrap (default), items squish

cardcardcardcard

wrap, flows to the next line

cardcardcardcard
.grid { display: flex; flex-wrap: wrap; gap: 12px; }

flex: 1 and align-self

flex:1 flex:2 (twice as wide) align-self:end
.a { flex: 1; }               /* grow 1 share */
.b { flex: 2; }               /* grow 2 shares */
.c { align-self: flex-end; }  /* override cross-axis for one child */
Gotcha: Flex children can't shrink below their content size by default, so long text overflows. Fix it with min-width: 0 (or overflow: hidden) on the flex child.

Common patterns

Nav bar

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

Card row that wraps

Card
flex: 1 1 160px, grows and shrinks from a 160px base
Card
Wraps on small screens
Card
No media query needed
.cards { display: flex; flex-wrap: wrap; gap: 12px; }
.card  { flex: 1 1 160px; } /* grow, shrink, basis 160px */
Exercise: Responsive card grid (20 min)
  1. Create a container with 6 cards (<article class="card">).
  2. .cards { display: flex; flex-wrap: wrap; gap: 12px; }
  3. .card { flex: 1 1 200px; border: 1px solid #ddd; padding: 12px; }
  4. Resize the window; it should wrap automatically. Try long text with min-width: 0.
Prev8: Display, Flow & Why Inline Feels Broken Next10: Grid