Skip to main content
Mohammad Shehadeh — home (MSH monogram, letter M filled with the Palestinian flag)

Auto-fit Vs Auto-fill

Published on
Last updated on
2 min read

For responsive CSS Grid layouts, knowing the difference between auto-fit and auto-fill lets you get the behavior you want without media queries.

Key Distinction

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:

style.css
1.wrapper {
2  display: grid;
3  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
4  grid-gap: 1rem;
5}

Try it out:

Auto-Fit

4 items Stretches items to fill available space

Item 1
Item 2
Item 3
Item 4
Min: 1
Max: 10
Watch out

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:

style.css
1.wrapper {
2  display: grid;
3  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
4  grid-gap: 1rem;
5}

Try it out:

Auto-Fill

3 items Maintains column width, creates empty columns

Item 1
Item 2
Item 3
Min: 1
Max: 10
Watch out

With auto-fill, the grid keeps item sizes consistent and preserves empty column spaces, for a more predictable layout.

Key Differences

  1. Space Distribution:

    • auto-fit collapses empty tracks and distributes space to existing items
    • auto-fill maintains empty tracks, preserving the intended column size
  2. Use Cases:

    • Use auto-fit when you want items to expand and fill the container
    • Use auto-fill when you want to maintain consistent item sizes with potential empty spaces

References

Related Articles

GET IN TOUCH

Let's work together

I build fast, accessible, and delightful digital experiences for the web. Whether you have a project in mind or just want to connect, I'd love to hear from you.

Get in touch

or reach out directly at hello@mohammadshehadeh.com