Flexbox
Wrap flex items
Let items form multiple lines, control line spacing, and decide when a one-dimensional wrapping layout should become a Grid instead.
By default flex items squeeze onto one line. When there are too many of them, they shrink until they can’t, and then they overflow. Wrapping fixes that by letting items move to a new line when they run out of room.
You enable it on the container. A list of tags is the classic case:
.tags {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
Now each tag keeps its natural width, and when the next one doesn’t fit it starts a new line. gap applies between lines too, not only between items on the same line.
Give items a useful minimum
Wrapping alone only moves items around. To get a layout where items fill each line and drop to the next when they get too narrow, give them a flexible basis:
.tags > * {
flex: 1 1 12rem;
}
Each item wants 12rem. If a line has spare room, the items on it grow to fill it. If an item can’t get 12rem, it wraps. This is how you get a row of cards that goes from four across to two across to one, with no media query.
Each line is sized on its own
Here is the thing people miss. The browser forms lines first, then sizes each line independently. Items on line two don’t know about items on line one.
So if the last line has one card, that card grows to the full width. And the cards on different lines don’t line up in columns, because there are no columns. There are only lines.
align-content
When the container is taller than all its lines together, align-content distributes the leftover cross-axis space between lines. space-between, center, flex-start, same values you know from justify-content.
It has no effect on a single line. If you set it and nothing happens, you probably have one line or the container is exactly as tall as its content.
When to switch to Grid
Flexbox is one-dimensional. It’s great for toolbars, navigation, button groups, tag lists, anything that flows in one direction and can break into lines.
The moment you need rows and columns to stay aligned, and the last row to keep the same column widths as the first, you want Grid. We’ll get there in the next module. Don’t fight Flexbox to make it behave like a table.
Try this on your tag list: resize the window slowly and zoom to 200%. Notice that lines break where the content forces them to, not at a device width. And tab through the items: wrapping changed where they sit visually, but the keyboard order is still the source order.
Lesson completed