CSS

Auto-Responsive Grid with `auto-fit` and `minmax`

Create highly adaptable and responsive grid layouts without media queries for column counts, using CSS Grid's `repeat(auto-fit, minmax())` function.

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

.grid-item {
  background-color: #007bff;
  color: white;
  padding: 20px;
  border-radius: 5px;
  text-align: center;
  font-size: 1.2em;
}

/* Basic HTML Structure for context:
<div class="grid-container">
  <div class="grid-item">Item 1</div>
  <div class="grid-item">Item 2</div>
  <div class="grid-item">Item 3</div>
  <div class="grid-item">Item 4</div>
  <div class="grid-item">Item 5</div>
  <div class="grid-item">Item 6</div>
</div>
*/
How it works: This snippet showcases a powerful CSS Grid feature for creating truly responsive layouts. The `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))` line automatically adjusts the number of columns based on the available space. Each column will be at least `250px` wide, but no wider than `1fr` (an equal fraction of the remaining space). When there's enough room, more columns are added; when space is tight, columns wrap to the next row. The `gap` property ensures consistent spacing between grid items, eliminating the need for complex margin calculations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs