CSS Grid Auto-fit, Auto-fill & minmax()
Create fully responsive grids without media queries using repeat(auto-fit, minmax()), auto-fill, and the grid auto-placement algorithm.
Overview
Key Points
- •repeat(auto-fit, minmax(250px, 1fr)) the most useful responsive grid pattern
- •auto-fit: collapses empty tracks so items expand to fill the container
- •auto-fill: keeps track positions even when empty items do not expand beyond max
- •minmax(200px, 1fr): at least 200px, at most 1 fraction of available space
- •grid-auto-rows: 1fr or a fixed height sizes auto-placed rows
- •grid-auto-flow: column fills by column instead of row
- •dense packing: grid-auto-flow: dense fills holes left by large items
Examples
Fully responsive card grid no media queries
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 24px;
padding: 24px;
}On a 300px screen: 1 column. On 600px: 2 columns. On 900px: 3 columns. Zero media queries.
auto-fill vs auto-fit comparison
/* auto-fit: 3 items in a 900px container → 3 equal columns */
.auto-fit { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
/* auto-fill: 3 items + empty columns → items stay at max 200px... */
/* Wait with 1fr max, auto-fill behaves like auto-fit (1fr absorbs space) */
/* The difference shows when max is a fixed value: */
.auto-fill { grid-template-columns: repeat(auto-fill, minmax(200px, 200px)); }
/* Items stay at 200px; empty tracks are kept as 200px gaps */
.auto-fit2 { grid-template-columns: repeat(auto-fit, minmax(200px, 200px)); }
/* Items stretch to fill empty tracks collapsed */The auto-fit vs auto-fill difference only matters when there are fewer items than available column slots.
Masonry-style grid with dense auto-placement
.photo-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-auto-rows: 200px;
gap: 8px;
grid-auto-flow: dense; /* fill holes automatically */
}
.photo-tall {
grid-row: span 2; /* tall photos take 2 rows */
}
.photo-wide {
grid-column: span 2; /* wide photos take 2 columns */
}Common Mistakes
- Using minmax(0, 1fr) instead of minmax(250px, 1fr) without a min-width, columns can collapse to 0 width
- Confusing auto-fit and auto-fill when max is 1fr they behave identically when max is a flexible value
- Forgetting gap or using margin instead margin adds to the total and can cause overflow
Note
For a photo gallery with equal-height rows, combine auto-fit with grid-auto-rows: a fixed height or aspect-ratio on the items. Use object-fit: cover on images to fill the cells without distortion.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4