10. Flexbox Layout
Flexbox is the modern way to arrange items in a row or column. Put display: flex on a parent (the container) and its children (the items) line up in a row. justify-content spreads items along the main direction, align-items aligns them across it, gap adds space between them, and flex-wrap lets them move to the next line when space runs out. Navbars, card rows and sidebars are all built with flexbox.
Key points
- display: flex on the parent starts the layout.
- flex-direction: column stacks items vertically.
- justify-content: space-between pushes items to the two ends.
- flex: 1 makes an item grow to fill the free space.
- Use gap instead of margins between items.
Example: A navbar and a card row
<nav class="bar">
<strong>MySite</strong>
<span>Home About Contact</span>
</nav>
<div class="row">
<div class="card">One</div>
<div class="card">Two</div>
<div class="card">Three</div>
</div>
<style>
.bar { display: flex; justify-content: space-between; align-items: center;
background: black; color: white; padding: 12px; }
.row { display: flex; gap: 12px; margin-top: 16px; }
.card { flex: 1; border: 2px solid black; padding: 20px; text-align: center; }
</style>
Show explanation
The bar uses space-between to put the name on the left and links on the right. The row shares its width equally between three cards.
Try it yourself
Edit the code below and press Run. The result appears in the preview underneath.
PREVIEW