Flexbox
Flexbox is a one-dimensional layout system — it arranges items in a single row or column and makes it easy to align, space out, and reorder them, without the old hacks of float and inline-block. It's the go-to tool for navbars, card rows, centering content, and any layout that flows in one direction.
The Flex Container
You turn any element into a flex container with display: flex. Every direct child
then automatically becomes a "flex item".
.container {
display: flex;
flex-direction: row; /* row | row-reverse | column | column-reverse */
flex-wrap: nowrap; /* nowrap | wrap | wrap-reverse */
justify-content: flex-start; /* flex-start | flex-end | center | space-between | space-around | space-evenly */
align-items: stretch; /* flex-start | flex-end | center | stretch | baseline */
align-content: flex-start; /* like align-items, but for multiple wrapped rows */
gap: 16px; /* space between items, both directions */
}
Two axes to remember:
flex-direction: row→ main axis is horizontal, cross axis is verticalflex-direction: column→ main axis is vertical, cross axis is horizontaljustify-contentalways controls the main axisalign-itemsalways controls the cross axis
The Flex Items
These properties go on the children, not the container:
.item {
flex-grow: 1; /* how much this item grows to fill extra space, relative to siblings */
flex-shrink: 1; /* how much this item shrinks when space is tight */
flex-basis: 200px; /* the item's starting size before growing/shrinking */
/* Shorthand: grow shrink basis */
flex: 1 1 200px;
/* Common shorthand — grow and shrink equally, ignore basis */
flex: 1;
/* Change this item's order without touching the HTML */
order: 2;
/* Override align-items for just this one item */
align-self: flex-end;
}
Full Examples
Example 1 — a simple navbar:
<nav class="navbar">
<div class="logo">GDW</div>
<ul class="nav-links">
<li><a href="/">Home</a></li>
<li><a href="/courses">Courses</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 24px;
}
.nav-links {
display: flex;
gap: 24px;
list-style: none;
}
Example 2 — perfectly centering content (a very common need):
.center-box {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Example 3 — equal-width card row that wraps on small screens:
.card-row {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 250px; /* grow, shrink, start at 250px — wraps when there's no room */
}