Container and items: the core idea
Flexbox works on two levels: the container (the parent you turn into a flex layout) and the items (its direct children, which flex arranges automatically).
That's it to get started โ every direct child of .container now lines up in a row automatically, instead of stacking vertically like normal block elements do.
flex-direction: row or column
justify-content: spacing along the main axis
This controls how items are spread out horizontally (assuming the default row direction):
| Value | Effect |
|---|---|
flex-start | Items bunched at the start (default) |
center | Items bunched in the middle |
space-between | First and last touch the edges, even spacing between |
space-around | Even spacing around every item, including the edges |
align-items: positioning on the cross axis
While justify-content handles horizontal spacing, align-items handles vertical alignment within the row (perfect for that classic "how do I vertically center this" problem):
justify-content: center; align-items: center; together is the single most common way to perfectly center anything โ a modal, a loading spinner, a hero section โ in modern CSS. It replaces a dozen old hacky centering tricks.
flex-wrap: what happens when items don't fit
Without flex-wrap: wrap, Flexbox tries to cram everything into one line, shrinking items until they're uncomfortably small. Adding it lets items flow onto new rows once they run out of horizontal space โ essential for anything that needs to work on mobile.
gap: spacing between items, the easy way
Before gap existed, spacing flex items apart meant adding margin to every child and subtracting it from the container โ messy. gap replaced all of that with one clean line, and it's supported everywhere modern.
flex-grow and flex-shrink: controlling individual items
flex-grow: 1 on an item tells it "take up whatever extra space is left" โ the classic pattern for a fixed-width sidebar next to a content area that fills the rest of the screen.
Try it yourself
<div class="nav"> containing a logo and three links. Give .nav display: flex, justify-content: space-between, and align-items: center. Watch the logo and links line up cleanly on one row, evenly spaced.
Level up: a 3-column card row
.card elements from Lesson 2 and wrap them in a container with display: flex, gap: 20px, and flex-wrap: wrap. Give each card flex: 1 so they share space equally. Resize your browser and watch them wrap onto a new row once the window gets narrow.
display: flex turns on Flexbox. justify-content and align-items handle alignment, flex-wrap keeps things responsive, and gap handles spacing cleanly. Together, they solve the layout problems that used to need hacks.