flex-wrap
Example
.cards {
display: flex;
}
.card {
width: 300px;
}.cards {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.card {
flex: 1 1 300px;
}Without flex-wrap, items shrink into one line; with it, they move to new lines once they hit 300px.
Common mistakes
- Items never wrap because they all have
flex-shrink: 1and no minimum size. - The last row's items stretch wider than the others with
flex: 1.
Key points
- Responsive rows of cards use
flex-wrap: wrapwith aflex-basisormin-width, so items wrap instead of overflowing. - Spacing between wrapped lines uses
gap, not negative margins.
Interview questions
Why are my flex items not wrapping?
The default is 'nowrap', and items shrink first. Add flex-wrap: wrap and give items a basis or minimum width.
How do I keep last-row items the same width?
Flexbox can't align items across rows. Use grid with repeat(auto-fill, minmax(300px, 1fr)) for equal columns.