Flexbox

One-dimensional layout for rows or columns: alignment, spacing, growing and shrinking items.

Beginner · about 4 hours · difficulty 2/5

Learn first: Box Model, Units and Typography

Flexbox lays items out along one axis at a time. It is the default tool for navbars, toolbars, centering, card rows and any component whose children line up.

Mental model

Set display: flex on a container and its direct children become flex items. The main axis follows flex-direction (row by default); the cross axis is perpendicular.

  • justify-content distributes items along the main axis (space-between, center).
  • align-items aligns them on the cross axis (center, stretch, baseline).
  • gap adds space between items; prefer it over margins.
  • flex-wrap: wrap lets items flow onto new lines.

Sizing items

flex: 1 is shorthand for grow 1, shrink 1, basis 0: items share free space equally. flex: 0 0 200px fixes a width. flex-shrink: 0 stops an icon from being squashed. A common bug is text refusing to truncate inside a flex item; the fix is min-width: 0 because flex items default to min-width: auto.

When not to use it

If you are trying to line things up in both rows and columns at once (a real grid, a page layout with sidebars), reach for CSS Grid. Flexbox and Grid are partners, not rivals.

Move on when you can build a responsive navbar, a vertically centred hero and a row of equal-height cards without looking anything up.

Key concepts

  • Main axis and cross axis
  • justify-content and align-items
  • gap
  • flex-grow, flex-shrink, flex-basis
  • flex-wrap
  • align-self and order
  • min-width: 0 truncation fix

Mini project

Build a responsive app header with a logo, a search bar that grows to fill space, and action icons that never shrink, plus a wrapping tag list below it.

Check yourself

What does flex: 1 actually expand to, and why do long words sometimes overflow a flex item?

Free resources