Flexbox is the tool that makes CSS layout finally feel easy. With a few properties you can build rows, navbars, centred content and evenly-spaced items. It is one of the most useful things you will learn.
Turning on Flexbox
Add <code>display: flex</code> to a container and its children become flex items, lined up in a row by default. The <code>gap</code> property adds even spacing between them.
<div class="row"><div class="item">1</div><div class="item">2</div><div class="item">3</div></div>.row{display:flex;gap:12px}
.item{background:#2563eb;color:#fff;padding:16px;border-radius:8px;flex:1;text-align:center}Aligning items
Two properties do most alignment. <code>justify-content</code> aligns items along the main axis (horizontal by default): start, center, space-between. <code>align-items</code> aligns on the cross axis (vertical): center, stretch.
| Property | Aligns |
|---|---|
| justify-content | Along the row (left↔right) |
| align-items | Across the row (top↕bottom) |
| gap | Space between items |
The classic centering trick
Centering used to be hard. With Flexbox it is three lines — <code>display:flex</code>, <code>justify-content:center</code>, <code>align-items:center</code>.
<div class="center"><span>Perfectly centered</span></div>.center{display:flex;justify-content:center;align-items:center;height:140px;background:#dbeafe;border-radius:12px}A simple navbar
<nav class="nav"><b>Logo</b><div class="links"><a href="#">Home</a><a href="#">About</a></div></nav>.nav{display:flex;justify-content:space-between;align-items:center;padding:14px 18px;background:#0f172a;color:#fff;border-radius:10px}
.links{display:flex;gap:16px}
.links a{color:#cbd5e1;text-decoration:none}.item { justify-content: center; }.row { display: flex; justify-content: center; }Putting flex properties like justify-content on the items instead of the container. They belong on the flex parent.
Use gap for spacing between flex items instead of margins — it is cleaner and does not add space at the edges.
Build a navbar with a logo on the left and links on the right using justify-content: space-between. Then centre a box of content with the three-line trick.
1. What turns on Flexbox?
2. Which aligns items horizontally (main axis)?
3. Where do flex properties like justify-content go?
- display: flex lines children up in a row; gap spaces them.
- justify-content aligns on the main axis; align-items on the cross axis.
- Centre anything with flex + justify-content:center + align-items:center.
- Flex properties go on the container, not the items.