Clean Markup

Responsive Card Grids Without Media Queries Using auto-fit and auto-fill

Responsive Card Grids Without Media Queries Using auto-fit and auto-fill

Creating responsive grid layouts historically meant writing a barrage of media queries: 1 column on mobile, 2 columns on tablet, 3 on desktop, and 4 on wide screens.

CSS Grid allows you to build intrinsic, fluid grid tracks that automatically wrap and adjust columns based on available space using repeat(), minmax(), and the keywords auto-fit or auto-fill.

Example

<ul class="card-grid">
  <li class="card">Item 1</li>
  <li class="card">Item 2</li>
  <li class="card">Item 3</li>
</ul>

Implementation

The key difference between auto-fit and auto-fill emerges when there are fewer items than can fit on a single row:

/* auto-fit: empty tracks collapse to 0px, expanding items to fill the row */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  padding: 0;
  list-style: none;
}

.card {
  padding: 24px;
  border: 1px solid var(--lightgray);
  border-radius: 8px;
  background: #ffffff;
}

Main Point: repeat(auto-fit, minmax(280px, 1fr)) creates completely fluid responsive card grids without requiring a single media query breakpoint.

Credits

Photo by Joel Filipe on Unsplash

← Home