Auto-fit vs Auto-fill in Grid

The Shared Setup

Both keywords are used together with repeat() to build a responsive grid, and both accept the same syntax - the difference only shows up when there are fewer items than the row could fit.

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}

What auto-fill Does

auto-fill calculates how many tracks of the given minimum size could fit in the row, and reserves that many tracks - even if there are not enough grid items to occupy all of them. The empty tracks still take up space, so existing items do not stretch to fill the row.

What auto-fit Does

auto-fit also calculates how many tracks could fit, but then collapses any empty tracks down to zero width, letting the actual items stretch (via 1fr) to fill the freed-up space.

The Visible Difference with Few Items

Scenarioauto-fillauto-fit
Row fits 5 tracks, only 2 items exist2 items shown, 3 empty invisible tracks remain, items stay minimum width2 items shown, empty tracks collapse, items stretch to fill the row
Row is completely fullIdentical to auto-fitIdentical to auto-fill

Which One to Use

For most card galleries and content grids, auto-fit gives the more natural-looking result, since a small number of items stretch to fill the available width rather than leaving unused blank space. auto-fill is more useful in the rarer case where consistent, unstretched item sizing matters more than filling the row - for example, a strict grid of fixed-size swatches.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.