MSH

Auto-fit Vs Auto-fill

Published on

When using CSS Grid to create responsive layouts, understanding the difference between auto-fit and auto-fill is crucial for achieving the desired behavior without relying on media queries.

Key Distinction

The key distinction lies in how these values handle available space within the grid container, affecting how grid items are sized and positioned.

Auto-Fit

The auto-fit keyword tells the grid to expand items to fill the available space within the container. This creates a more spread-out layout when there aren't enough items 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:

Watch out

Notice how auto-fit makes items expand to fill the entire width, which can result in wider items when there aren't enough elements to fill all columns.

Auto-Fill

In contrast, auto-fill maintains the specified item size and keeps empty column spaces reserved, rather than expanding the 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:

Watch out

With auto-fill, the grid maintains consistent item sizes and preserves empty column spaces, creating 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

GET IN TOUCH

Let's work together

I build exceptional and accessible digital experiences for the web

WRITE AN EMAIL

or reach out directly at hello@mohammadshehadeh.com