Flexbox
One-dimensional layout
Flexbox arranges items in a row or a column and handles spacing and alignment for you. Make the parent a flex container:
.container { display: flex; }
Container properties
| Property | What it does | Common values |
|---|---|---|
flex-direction | main axis | row (default), column |
justify-content | alignment along the main axis | flex-start, center, space-between, space-around |
align-items | alignment on the cross axis | stretch, center, flex-start |
gap | space between items | 16px |
flex-wrap | allow new lines | wrap |
Item properties
flex: 1takes an equal share of the free space.flex: 0 0 200pxis a fixed 200 px that won't grow or shrink.align-selfoverrides alignment for one item.orderchanges the visual order (keep it rare for accessibility).
Patterns you'll use constantly
- Centre anything:
display: flex; justify-content: center; align-items: center; - Navbar: logo left, links right with
justify-content: space-between. - Push one item right: give it
margin-left: auto. - Wrapping cards:
flex-wrap: wrap; gap: 16px;, with childrenflex: 1 1 250px;.
Example
<style>
body { font-family: sans-serif; margin: 0; }
.nav {
display: flex; justify-content: space-between; align-items: center;
padding: 12px 20px; background: #111827; color: white;
}
.nav ul { display: flex; gap: 16px; list-style: none; margin: 0; padding: 0; }
.cards { display: flex; flex-wrap: wrap; gap: 16px; padding: 20px; }
.card {
flex: 1 1 200px;
padding: 20px; border-radius: 12px; background: #eef2ff;
}
.center { display: flex; justify-content: center; align-items: center; height: 120px; background: #f3f4f6; }
</style>
<nav class="nav">
<strong>Logo</strong>
<ul><li>Home</li><li>Blog</li><li>Contact</li></ul>
</nav>
<div class="cards">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
</div>
<div class="center">Perfectly centred</div>