Lessons · HTML and CSS · flexbox
Flexbox
display: flex lays out direct children along one line, a row by default. gap spaces them, align-items lines them up across the row, and an auto margin pushes one item to the far end.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Navigation bars, toolbars, a label beside a field, a card's title beside its badge: flex is the daily tool for 'put these next to each other and line them up'.
How to think about it
Put display: flex on the parent, never on the children. Then: gap for spacing, align-items: center to line up, margin-left: auto on the item that belongs at the end.
Worked example
<div class="bar"><a>Home</a><a>Docs</a><a class="end">Sign in</a></div>Three links in a container.
.bar { display: flex; gap: 12px; align-items: center; }A row, 12px between items, everything centred across the row..end { margin-left: auto; }An auto margin takes all the free space: the last link goes to the far end.Your turn
Put the space between the items, not around them.
.bar { display: flex; : 16px; }Write a page and watch it render
The trap
Putting display: flex on the children. Flex is a property of the container; the children only need to be its direct children.