Use auto-fit for a row of cards that should fill the width. Use auto-fill when a short row should keep its columns at their minimum size instead of stretching.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1rem;
}
Both create as many 240px-minimum columns as fit, and both wrap items onto new rows as the container narrows, with no media query.
The one difference
They diverge only when there are fewer items than columns. Say the container fits four columns and there are two items:
auto-fillkeeps four tracks, two of them empty. The two items are each one quarter wide.auto-fitcollapses the empty tracks to zero. The two items grow to half the width each.
Cards, tiles, image galleries: auto-fit, so a single result doesn’t sit in a narrow column. Form fields or a toolbar where one control shouldn’t balloon: auto-fill.
Gotchas
minmax(240px, 1fr)overflows a container narrower than 240px. Wrap the minimum:minmax(min(240px, 100%), 1fr).- Items with
min-width: autocontent, like a long unbroken string, still force a track wider than its minimum. Addmin-width: 0to the item. - To cap the number of columns, cap the container’s width, or use
max-widthon the items; the repeat keyword has no maximum.