Before flexbox, putting things side by side or centering something in CSS was a headache. Flexbox (“flexible box layout”) was made to fix that. It arranges a group of items in one direction, a row or a column, and gives you simple control over their spacing, alignment and size.
Two roles: container and items
- The flex container is the parent. You write
display: flexon it. - The flex items are its direct children. They automatically become flex items.
<style>
.container { background: #f4f9fc; border: 2px dashed #1a5276; padding: 8px; }
.box { background: #d94a00; color: #fff; padding: 12px 18px; font-weight: bold; }
.container { display: flex; }
</style>
<div class="container"><div class="box">1</div><div class="box">2</div><div class="box">3</div></div>
That one line, display: flex, put three blocks that would have stacked into a row. Remove it and press Run to see the difference.
The two axes
Flexbox thinks in two directions:
- The main axis is the direction the items flow (by default, left to right).
- The cross axis runs at 90 degrees to it (top to bottom).
Almost every flexbox property is about one of those axes. justify-content works on the main axis, align-items on the cross axis. Keep that in mind and the rest will make sense.
What you get for free
- Items sit in a row, side by side.
- All items stretch to the same height.
- Items do not wrap to a new line unless you ask them to.
- Extra space is left at the end, and you can distribute it.
What flexbox is good for
- Navigation bars and toolbars
- Rows of cards
- Centering things
- Forms with a label and a field side by side
- Any layout that is one-dimensional: a row or a column
For layouts with rows and columns together, see CSS Grid.
Only direct children
display: flex affects the container’s immediate children. A grandchild is not a flex item. If it needs to be laid out with flexbox, make its parent a flex container as well.