Auto-fit Vs Auto-fill
For responsive CSS Grid layouts, knowing the difference between auto-fit and auto-fill lets you get the behavior you want without media queries.
The difference is how each value handles available space in the grid container, which affects how grid items are sized and positioned.
Auto-Fit
The auto-fit keyword tells the grid to expand items to fill the available space in the container. This spreads items out when there aren't enough to fill all possible columns.
Example Usage:
Try it out:
Auto-Fit
4 items • Stretches items to fill available space
auto-fit makes items expand to fill the entire width, so items get wider when there aren't enough to fill all columns.
Auto-Fill
In contrast, auto-fill keeps the specified item size and reserves empty column spaces instead of expanding items to fill the available space.
Example Usage:
Try it out:
Auto-Fill
3 items • Maintains column width, creates empty columns
With auto-fill, the grid keeps item sizes consistent and preserves empty column spaces, for a more predictable layout.
Key Differences
-
Space Distribution:
auto-fitcollapses empty tracks and distributes space to existing itemsauto-fillmaintains empty tracks, preserving the intended column size
-
Use Cases:
- Use
auto-fitwhen you want items to expand and fill the container - Use
auto-fillwhen you want to maintain consistent item sizes with potential empty spaces
- Use