Flexbox

Flexbox lays out items in one direction — a row or a column — and distributes space between them. It makes navigation bars, toolbars, card rows, centring and equal-height columns easy, and it adapts naturally to different screen sizes.

Creating a flex container

Try it yourself
Result

display: flex on a parent makes its direct children flex items, laid out in a row. gap adds space between them — no margins needed.

Main axis and cross axis

Flexbox works along two axes. The main axis follows flex-direction (a row by default); the cross axis runs perpendicular to it. justify-content aligns along the main axis, align-items along the cross axis.

Try it yourself
Result
Accessibility: row-reverse, column-reverse and order change only the visual order. Keyboard focus and screen readers still follow the HTML order, so avoid using them to rearrange meaningful content.

justify-content: main-axis alignment

Try it yourself
Result

align-items: cross-axis alignment

Try it yourself
Result

The default, stretch, makes all items the same height — which is how flexbox gives you equal-height columns for free.

Wrapping

Try it yourself
Result

By default, flex items squeeze onto one line. flex-wrap: wrap lets them wrap onto new lines; align-content then distributes those lines. flex-flow is a shorthand for direction and wrap.

Common patterns

Try it yourself
Result

margin-left: auto on a flex item pushes it (and everything after it) to the far end — the classic way to put "Log in" on the right of a navbar.

Container properties reference

PropertyControls
flex-directionrow, column, and reversed versions
flex-wrapnowrap, wrap
justify-contentMain-axis distribution
align-itemsCross-axis alignment of items
align-contentCross-axis distribution of wrapped lines
gap, row-gap, column-gapSpacing between items

The next lesson covers properties on the items themselves: flex-grow, flex-shrink, flex-basis, align-self and order.

Try it yourself

Try it yourself
Result