Flexible Card Grid with Flexbox
Create a responsive card grid using Flexbox wrap. Cards adapt to container width and maintain consistent sizing with equal height rows.
Detailed Explanation
Responsive Card Grid with Flexbox
Card grids are ubiquitous in modern web design — product listings, blog archives, team members, feature showcases. Flexbox with flex-wrap creates a responsive card grid that adapts to any container width.
CSS Code
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 24px;
}
.card {
flex: 1 1 300px;
max-width: 400px;
display: flex;
flex-direction: column;
}
.card-body {
flex: 1;
}
.card-footer {
flex: 0 0 auto;
}
How It Works
- Grid container:
flex-wrap: wrapallows cards to flow onto new lines.gap: 24pxprovides consistent spacing. - Cards:
flex: 1 1 300pxmeans each card starts at 300px minimum and grows to fill space.max-width: 400pxprevents cards from getting too wide. - Card internals: Each card is itself a column flex container, ensuring the footer stays at the bottom regardless of content height.
Equal Height Cards
Flexbox automatically gives all items in the same row equal height (when align-items: stretch is set, which is the default). This means all cards in a row are the same height, even if they have different amounts of content.
By making each card a column flex container with flex: 1 on the body, the card body expands to fill the available space, pushing the footer to the bottom of every card consistently.
Handling the Last Row
The last row often has fewer items. With flex-grow: 1, those items stretch wider than items in full rows. Solutions:
/* Option 1: Don't grow */
.card {
flex: 0 1 300px;
}
/* Option 2: Use max-width */
.card {
flex: 1 1 300px;
max-width: calc(33.333% - 16px);
}
When to Use CSS Grid Instead
For true grid behavior with consistent columns, CSS Grid's grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)) is often a better choice. Flexbox card grids work best when you want items to fill space flexibly.
Use Case
Use this pattern for product listing pages, portfolio galleries, blog post archives, team member displays, or any collection of similarly-structured content cards. The Flexbox approach provides responsive behavior with equal-height rows.