Flexbox

One-dimensional layout done properly: main vs cross axis, alignment, growth factors, and the properties that trip people up.

Think in one axis

Flexbox lays items along a single line β€” the main axis (flex-direction) with the cross axis perpendicular to it. Row (default) means main is horizontal; column makes main vertical and swaps what align/justify control.

.row {
  display: flex;
  gap: 12px;
  justify-content: space-between; /* along main   */
  align-items: center;            /* across cross */
}
PropertyAxisEffect
justify-contentmainDistributes the whole row: start, center, space-between
align-itemscrossAligns each item within the line
align-selfcrossOverride for one item
gapbothSpacing without margin maths

Item properties

.item {
  flex: 1 1 200px;   /* grow shrink basis */
}
.item--fixed { flex: 0 0 auto; }
.push-right  { margin-left: auto; }
  • flex-grow β€” share of leftover space to absorb (default 0).
  • flex-shrink β€” willingness to shrink when space runs out (default 1).
  • flex-basis β€” starting size before grow/shrink maths.
  • flex: 1 is shorthand for 1 1 0% β€” a genuinely equal split, since the basis is zero.
πŸ’‘
Use the flex shorthand rather than the three longhands. flex: 1 1 auto sizes items by content first, which is why "equal columns" often come out unequal.

Wrapping and common gotchas

.wrap { display: flex; flex-wrap: wrap; gap: 16px; }
.card { flex: 1 1 240px; min-width: 0; } /* min-width lets text shrink */
  • Flex items do not collapse their margins β€” that is why gaps look different from margin-based layouts.
  • min-width: auto on flex items prevents shrinking below content size, causing overflow. min-width: 0 fixes truncated text.
  • A flex item's percentage height needs a definite parent height to resolve.
  • Multi-line wrapping changes alignment handling β€” align-content then distributes the lines.

FAQ

Flexbox or Grid?
Flexbox for a single row or column where content drives sizing. Grid for two-dimensional arrangements where you define the tracks. Both compose happily β€” flex inside a grid cell is normal.
Why does my item overflow instead of shrinking?
Default min-width: auto. Add min-width: 0 (or overflow: hidden) to the item.

CSS Grid The box model

Last refreshed 2026-09-17.