flex-wrap & flex-basis
Cards that wrap
Lesson 1 of 20 · 9 min · Module 1: Layouts that adapt
A row of cards looks great on a laptop and terrible on a phone, where the cards get squeezed until the text pokes out. With wrapping, flexbox moves cards to a new line instead of squeezing them.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Let flex items wrap onto new lines
- Control item size with flex-grow, flex-shrink and flex-basis
- Build responsive rows without media queries
The idea
flex-wrap: wrap lets flex items continue on the next line. flex: 1 1 220px is shorthand for grow, shrink and basis: each card starts at 220px, may grow to fill leftover space, and may shrink when needed. Together they give you responsive rows without a single media query.
.tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
01Squeezing versus wrapping
Without flex-wrap, flexbox keeps every item on one line and shrinks them down to their minimum content width. Long words then poke out of the cards and the row overflows the screen.
02Read the flex shorthand
flex: 1 1 220px means flex-grow: 1, flex-shrink: 1 and flex-basis: 220px. The basis is the starting size, grow decides who takes leftover space, and shrink decides who gives up space when a line is too full.
.card { flex: 1 1 220px; }
/* is the same as */
.card {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 220px;
}
03Uneven last rows
When three cards fit per row and you have four, the fourth card grows to fill the whole last row. If every card must keep the same width, the auto-fit grid in the next lesson is the better tool.
Your turn
.cards wrap its items onto new lines, with gap: 16px. Replace the fixed width of .card with flex: 1 1 220px. On a 390px screen, every card must fit.What the checks look for
- The card row wraps onto new lines
- Cards are 16px apart
- Every card starts from a 220px basis
- Every card can grow to fill its row
- All cards fit a 390px screen
Take this with you
flex-wrap plus a flex-basis gives you rows that adapt to any screen.
Go a little further
Give the first card flex: 2 1 220px and watch it take twice as much leftover space as the others.