I want cards at least 260px wide that fill the row and wrap to fewer columns on smaller screens, without writing breakpoints. I have seen auto-fill and auto-fit. What is the difference?
DEV3 Developer Forum
How do I make a responsive card grid without media queries using auto-fit and minmax?
Every post is reviewed first. Usually reviewed within 24 hours.
1 reply
The pattern
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(260px, 100%), 1fr));
gap: 1rem;
}
The browser creates as many columns as fit with a minimum of 260px and shares the leftover space equally (1fr). On narrow screens it drops to one column automatically.
Why min(260px, 100%)
Without it, on a screen narrower than 260px a single column would overflow. min() caps the minimum at the container width.
auto-fit vs auto-fill
Both create as many tracks as fit. If there are fewer items than tracks:
auto-fillkeeps the empty tracks, so your 2 cards stay at 260px-ish wide with blank space on the right.auto-fitcollapses the empty tracks, so the 2 cards stretch to fill the row.
Pick auto-fit for stretching cards, auto-fill when you want a consistent card width regardless of count.
Tailwind
<div class="grid grid-cols-[repeat(auto-fit,minmax(min(260px,100%),1fr))] gap-4">
...
</div>
or the classic breakpoint version: grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3. Use breakpoints when you want an exact number of columns, auto-fit when you want content-based flow.
Pitfalls
- Long unbreakable content inside cards can force overflow; give cards
min-width: 0andoverflow-wrap: anywhere. - Equal-height cards come for free in grid (
align-items: stretchis the default). Put the button at the bottom withdisplay: flex; flex-direction: columnon the card andmargin-top: autoon the button.
Build one visually with the CSS grid generator.