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 */
}| Property | Axis | Effect |
|---|---|---|
justify-content | main | Distributes the whole row: start, center, space-between |
align-items | cross | Aligns each item within the line |
align-self | cross | Override for one item |
gap | both | Spacing 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: 1is shorthand for1 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: autoon flex items prevents shrinking below content size, causing overflow.min-width: 0fixes truncated text.- A flex item's percentage height needs a definite parent height to resolve.
- Multi-line wrapping changes alignment handling β
align-contentthen 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.Related
Last refreshed 2026-09-17.