Auto-Fit: Collapsing Empty Tracks
You'll learn how repeat(auto-fit, ...) differs from auto-fill by collapsing empty grid tracks to create truly flexible layouts.
The Core Idea
While auto-fill creates as many tracks as possible (even empty ones), auto-fit behaves differently: it creates tracks and then collapses any empty ones to zero width. This means your grid items will stretch to fill all available space, rather than leaving gaps where empty tracks would be.
Think of it like folding chairs at an event. With auto-fill, you set up all the chairs even if guests don't arrive (empty tracks remain). With auto-fit, you only keep chairs that are occupied and remove the empty ones, letting the seated guests spread out more comfortably.
How Auto-Fit Works
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
In this pattern:
- Grid creates as many 200px-minimum tracks as fit
- If fewer items exist than tracks, empty tracks collapse
- The
1frmaximum allows existing items to expand into freed space - Items grow to fill the entire container width
Auto-Fit vs Auto-Fill
The difference shines when you have fewer items than possible tracks. With auto-fill, items stay at their maximum size with empty space remaining. With auto-fit, items expand to consume all container space because empty tracks disappear.
Key Takeaway: Use repeat(auto-fit, minmax(...)) when you want grid items to stretch and fill all available space by collapsing unused tracks, creating truly responsive layouts that adapt both to screen size and content quantity.