CSS

Build a Responsive Grid with Auto-Fitting Items and Gaps

Dynamically adjust the number and size of grid columns using `auto-fit`, `minmax()`, and `gap` for highly responsive layouts, ideal for card UIs.

.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f0f0f0;
}

.card {
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  text-align: center;
}

/* Basic HTML structure for context (e.g., 6 cards) */
/*
<div class="card-container">
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
  <div class="card">Card 4</div>
  <div class="card">Card 5</div>
  <div class="card">Card 6</div>
</div>
*/
How it works: This snippet demonstrates creating a highly responsive grid layout where items (like cards) automatically adjust their number and size to fit the available space. `display: grid` initiates the grid. `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))` is key: `repeat(auto-fit, ...)` creates as many columns as can fit, while `minmax(250px, 1fr)` ensures each column is at least `250px` wide but will grow up to `1fr` (an equal fraction of the remaining space). `gap` adds consistent spacing between grid items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs