Responsive Flexbox Wrap Layout
Create a responsive layout that automatically wraps items to new lines when the container is too narrow. Uses flex-wrap and flex-basis for breakpoint-free responsiveness.
Detailed Explanation
Responsive Wrapping with Flexbox
One of Flexbox's most powerful features is flex-wrap: wrap, which allows items to flow onto new lines when the container becomes too narrow. Combined with flex-basis, you can create responsive layouts without media queries.
CSS Code
.container {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.item {
flex: 1 1 300px;
}
How It Works
The shorthand flex: 1 1 300px means:
flex-grow: 1— Items grow to fill available spaceflex-shrink: 1— Items can shrink if neededflex-basis: 300px— Each item wants to be at least 300px wide
When the container is wide enough, items sit side by side. As the container shrinks below the point where items can maintain their 300px minimum, items wrap to the next line. Each line's items then grow to fill the available width.
The Math Behind Wrapping
For a container of width W with gap G and N items per row:
- Items per row = floor((W + G) / (flex-basis + G))
- On a 960px container with 16px gap and 300px basis: floor(976/316) = 3 items per row
Progressive Enhancement
/* Mobile-first: single column */
.item {
flex: 1 1 100%;
}
/* When space allows: multi-column */
@media (min-width: 600px) {
.item {
flex: 1 1 calc(50% - 8px);
}
}
@media (min-width: 900px) {
.item {
flex: 1 1 calc(33.333% - 11px);
}
}
Common Gotcha
The last row often has fewer items, causing them to stretch wider than items in full rows. To maintain consistent sizing, use flex-grow: 0 or set a max-width on items. Alternatively, consider CSS Grid with auto-fill for true grid behavior.
Use Case
Use this pattern for product listing pages, portfolio galleries, blog post grids, or any layout where items should adapt to the available width. The flex-wrap approach provides smooth, breakpoint-free responsive behavior.