DEV3 Technologies home

DEV3 Developer Forum

How do I make a responsive card grid without media queries using auto-fit and minmax?

dev3 ·

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?

#css#grid#responsive

0

1 reply

dev3 · Accepted answer

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-fill keeps the empty tracks, so your 2 cards stay at 260px-ish wide with blank space on the right.
  • auto-fit collapses 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: 0 and overflow-wrap: anywhere.
  • Equal-height cards come for free in grid (align-items: stretch is the default). Put the button at the bottom with display: flex; flex-direction: column on the card and margin-top: auto on the button.

Build one visually with the CSS grid generator.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.