auto-fill & auto-fit
These keywords let the browser decide how many columns to create, making fully responsive grids without any media queries. They go inside repeat() in place of a fixed count.
1. auto-fill β Fill with as Many Columns as Possible
repeat(auto-fill, ...) creates as many column tracks as will fit in the container, based on the minimum size. Empty tracks are preserved (they still take up space).
.container {
display: grid;
grid-template-columns:
repeat(auto-fill, minmax(100px, 1fr));
gap: 8px;
/* browser creates as many 100px+ columns as fit */
}2. auto-fit β Stretch Items to Fill Space
repeat(auto-fit, ...) works like auto-fill, but collapses empty tracks to 0 width. This causes the remaining items to stretch and fill the entire row.
.container {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(100px, 1fr));
gap: 8px;
/* empty tracks collapse β items stretch */
}3. auto-fill vs auto-fit β Side by Side
The key difference: with fewer items than columns fit, auto-fill keeps empty tracks (items don't stretch), while auto-fit collapses empty tracks (items DO stretch to fill the row).
/* auto-fill: keeps empty tracks */ .fill { grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); } /* auto-fit: collapses empty tracks */ .fit { grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); } /* When items fill all columns: identical behavior */
4. Responsive Card Grid (Classic Pattern)
The most popular use case: a card grid that automatically adjusts columns based on available width. Cards are at least 200px wide and grow to fill space. Zero media queries needed.
/* classic responsive card grid */ .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 1.5rem; } /* - narrow screen: 1 column (< 200px) - medium screen: 2β3 cols (400β600px) - wide screen: 4β5+ cols (800px+) No media queries! */
5. Setting Column Limits with clamp()
Combine clamp() with auto-fill to control the min and max number of columns. For example, to ensure at least 2 but at most 4 columns.
/* Advanced: guarantee min 2 columns */ .container { grid-template-columns: repeat(auto-fill, minmax(max(120px, 25%), 1fr)); /* each col is at least 25% OR 120px, whichever is larger */ /* = always at least 4 columns if container > 480px */ } /* Simple approach: use a min-width container */ .cards-min-2 { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); min-width: 400px; /* ensures at least 2 cols */ }