CSS Grid Auto-Fit: Responsive Layouts Without Media Queries
One line of CSS replaces all your breakpoints. Here's how CSS Grid's auto-fit gives you fluid, responsive columns with zero @media rules.
Technologies Discussed
The Problem
You're writing CSS for a card grid. You add a breakpoint for 3 columns at 1200px, 2 columns at 768px, 1 column at 480px. Then the design changes. Now you're maintaining five media queries for one component.
There's a better way.
The One-Liner
css
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
}
That's it. No media queries. No breakpoints. It just works.
How It Works
- **`repeat(auto-fit, ...)`** — creates as many columns as fit in the container
- **`minmax(280px, 1fr)`** — each column is *at least* 280px wide, and expands to fill available space
When the viewport shrinks below ~560px, you automatically drop to one column. At 840px you get two. At 1120px, three. The browser does the math.
auto-fit vs auto-fill
These are easy to confuse:
css
/* auto-fill: keeps empty ghost columns, doesn't stretch items */
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));/* auto-fit: collapses empty columns, stretches items to fill the row */ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
For most card grids, **auto-fit** is what you want — items expand to fill the row naturally.
Real-World Example
css
/* Before: 3 breakpoints, brittle */
.cards {
display: grid;
grid-template-columns: 1fr;
}
@media (min-width: 600px) {
.cards { grid-template-columns: 1fr 1fr; }
}
@media (min-width: 900px) {
.cards { grid-template-columns: 1fr 1fr 1fr; }
}/* After: zero breakpoints, bulletproof */ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1.5rem; }
When NOT to Use This
This pattern works great for cards, thumbnails, and content tiles. Avoid it when you need a *specific* number of columns regardless of container size — for example, a fixed 2-column comparison layout. Use explicit column counts there.
Takeaway
`repeat(auto-fit, minmax(min, 1fr))` is one of the most powerful CSS Grid features. Learn this pattern once, and you'll reach for it constantly.