CSS

Flexbox: Responsive Card Layout with `flex-wrap`

Build a fluid and responsive grid of cards that automatically adjusts item count per row based on viewport size, leveraging Flexbox `flex-wrap`, `gap`, and `flex-basis` for dynamic layouts.

.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px; /* Space between cards */
  padding: 20px;
  background-color: #f5f5f5;
}

.card {
  flex: 1 1 calc(33.333% - 20px); /* Basis for 3 columns, accounting for gap */
  min-width: 250px; /* Minimum width before wrapping */
  box-sizing: border-box;
  background-color: white;
  border: 1px solid #ddd;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  text-align: center;
}

@media (max-width: 768px) {
  .card {
    flex: 1 1 calc(50% - 20px); /* Two columns on medium screens */
  }
}

@media (max-width: 480px) {
  .card {
    flex: 1 1 100%; /* Single column on small screens */
  }
}
How it works: This snippet creates a responsive card grid using Flexbox. The `.card-container` uses `display: flex` and `flex-wrap: wrap` to allow cards to flow to the next line. Each `.card` is given `flex: 1 1 calc(33.333% - 20px)`. `flex-basis` (the third value) determines its initial size, `flex-grow: 1` allows it to expand, and `flex-shrink: 1` allows it to shrink. The `calc()` function precisely accounts for the `gap` to create a clean multi-column layout that adapts with media queries.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs