HTML & CSS Interview Question #99
What is the difference between auto-fit and auto-fill in CSS Grid?
CSS Layout, Display, Positioning, Flexbox & Grid Mid-Level Intermediate
Quick Interview Answer
Both auto-fit and auto-fill repeat tracks according to available space. auto-fill can preserve empty generated tracks when there is room for more columns, while auto-fit collapses empty repeated tracks so existing items can expand into the available space.
Detailed Explanation
Both auto-fit and auto-fill repeat tracks according to available space. auto-fill can preserve empty generated tracks when there is room for more columns, while auto-fit collapses empty repeated tracks so existing items can expand into the available space.
The difference becomes most visible when the container has room for more tracks than there are items. The appropriate choice depends on whether empty track structure should remain or existing items should stretch.
Code Example
.fit-grid {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(180px, 1fr));
}
.fill-grid {
display: grid;
grid-template-columns:
repeat(auto-fill, minmax(180px, 1fr));
}