Auto-Fill vs Auto-Fit: When to Use Each
You'll learn when to choose auto-fill versus auto-fit to control how your grid handles extra space.
The Core Difference
Both auto-fill and auto-fit work with repeat() to create responsive grids without media queries, but they behave differently when there's leftover space:
auto-fillcreates as many tracks as will fit, even if they're empty. It fills the grid container with tracks.auto-fitcreates tracks only for existing items, then collapses any empty ones to zero width.
Think of it like theater seating: auto-fill is like reserving all available seats in a row (empty seats stay empty). auto-fit is like only setting up chairs for the people who actually showed up.
When to Use Each
Use auto-fill when:
- You want consistent spacing, even if some tracks are empty
- Items should stay the same size regardless of how many exist
- You're adding items dynamically and want space reserved
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1rem;
}
Use auto-fit when:
- You want items to expand and fill all available space
- The number of items is fixed or unknown
- You prefer items to grow wider when there are fewer of them
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
With three items in a wide container, auto-fill might leave empty space on the right, while auto-fit would let those three items stretch wider to fill the entire container.
Key Takeaway: Use auto-fill to maintain consistent sizing with reserved space, and auto-fit to let items expand when there's extra room.