CSS
Achieve Equal Height Cards or Grid Items with Flexbox
Ensure all items in a row maintain uniform height regardless of content length, perfect for card layouts or product displays using CSS Flexbox.
.card-container {
display: flex;
flex-wrap: wrap; /* Allows cards to wrap to the next line */
gap: 20px; /* Spacing between cards */
padding: 20px;
background-color: #eee;
}
.card {
flex: 1 1 calc(33.333% - 20px); /* Approx 3 cards per row, adjusting for gap */
display: flex; /* Make card content a flex container too */
flex-direction: column; /* Stack content vertically */
background-color: #fff;
border: 1px solid #ddd;
padding: 15px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
box-sizing: border-box; /* Include padding/border in width calculation */
}
.card-title {
font-weight: bold;
margin-bottom: 10px;
}
.card-content {
flex-grow: 1; /* Pushes card-footer to the bottom if present */
margin-bottom: 10px;
}
.card-footer {
margin-top: auto; /* Sticks footer to the bottom of the card */
color: #666;
font-size: 0.9em;
}
How it works: This snippet provides a robust solution for creating card-like layouts where all items in a row have the same height, even if their content varies. By setting `display: flex` on the `.card-container`, all direct children (`.card` items) in a row will automatically stretch to the height of the tallest item in that row (due to `align-items: stretch` being the default Flexbox behavior).
`flex-wrap: wrap` ensures cards move to the next line when space runs out. The `flex` property on the `.card` items controls their sizing and responsiveness. Additionally, each `.card` itself is a flex container (`display: flex; flex-direction: column;`), allowing internal elements like a footer to stick to the bottom using `margin-top: auto`.