CSS Grid auto-fit vs auto-fill
Published on
csstil
CSS Grid auto-fit vs auto-fill
Today I learned the subtle but important difference between auto-fit and auto-fill in CSS Grid.
The Difference
- auto-fill: Creates as many columns as can fit, even if they’re empty
- auto-fit: Collapses empty columns and stretches items to fill available space
Example
/* auto-fill - keeps empty columns */
.grid-auto-fill {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
/* auto-fit - collapses empty columns */
.grid-auto-fit {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}Use auto-fit when you want items to fill the container, and auto-fill when you want to maintain column structure even with fewer items.