The Flex Container

What this is. Flexbox arranges children along one axis and distributes the leftover space between them. You turn it on by setting display: flex on the parent, and from that moment its direct children become flex items.

What problem it solves. Before Flexbox, centering a box vertically was genuinely difficult, and putting a logo on the left with links on the right meant floats and clearfixes. Flexbox replaced a decade of workarounds with two or three declarations.

✦ The container controls the children

This is the part that trips people up. You do not tell a link to sit on the right. You tell its parent how to distribute space, and the link ends up there. Almost every Flexbox property goes on the container, not on the items.

Main axis and cross axis

ROW (DEFAULT)

flex-direction: row

main axis:  left to right
cross axis: top to bottom

COLUMN

flex-direction: column

main axis:  top to bottom
cross axis: left to right
Compare → justify-content always works along the main axis. align-items always works along the cross axis. Change flex-direction and those two swap meaning, which is why remembering the axes matters more than remembering the property names.
LIVE PREVIEW
loading editor…

Two flex containers nested: the bar spreads its two children apart, and the nav inside spaces its links evenly.

Your turn → Change justify-content on .bar to center, then to flex-end. Then delete it entirely and see the default, which is flex-start.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Alignment, Wrapping, and Growth →
← Back