CSS
Responsive Card Layout with Dynamic Wrapping using Flexbox
Build a flexible and responsive card grid that automatically wraps items to new lines and maintains consistent spacing, ideal for product listings or image galleries.
.card-container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next line */
justify-content: flex-start; /* Aligns items to the start of the line */
gap: 20px; /* Space between cards */
padding: 20px;
background-color: #f0f0f0;
font-family: sans-serif;
}
.card {
flex: 1 1 280px; /* Allows items to grow, shrink, and have a base width */
background-color: white;
border: 1px solid #ddd;
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
display: flex;
flex-direction: column; /* Content inside card stacks vertically */
min-width: 250px; /* Ensures cards don't get too small */
}
.card h3 {
margin-top: 0;
color: #333;
}
.card p {
flex-grow: 1; /* Makes paragraph take up available space */
color: #555;
}
How it works: This snippet creates a highly responsive card layout using Flexbox. By combining `display: flex` with `flex-wrap: wrap`, cards automatically flow to the next line as screen width changes. The `gap: 20px` property ensures consistent spacing between cards. The `flex: 1 1 280px` declaration on each `.card` is crucial: it allows cards to grow (`1`), shrink (`1`), and maintain a preferred width of `280px`. This makes the layout fluid: more cards fit on wider screens, and they wrap neatly on narrower ones, creating a dynamic grid.