What is the difference between auto-fill and auto-fit?

Solution 1:

The key is to use auto-fill instead of auto-fit.


When the repeat() function is set to auto-fit or auto-fill, the grid container creates as many grid tracks (columns/rows) as possible without overflowing the container.

Note that as the grid container is being rendered, the presence of grid items is irrelevant. The container just lays out the columns and rows as instructed, creating grid cells. It doesn't care if the cells are occupied or unoccupied.

With auto-fit, when there are not enough grid items to fill the number of tracks created, those empty tracks are collapsed.

Taking your code as an example, when there aren't enough grid items to fill all the columns in the row, those empty columns are collapsed. The space that was used by the empty columns becomes free space, which is then evenly distributed among existing items. By absorbing the free space, the items grow to fill the entire row.

With auto-fill, everything is the same as auto-fit, except empty tracks are not collapsed. They are preserved. Basically, the grid layout remains fixed, with or without items.

That's the only difference between auto-fill and auto-fit.

Here's an illustration of three grid items with auto-fill:

grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));

enter image description here

Here's an illustration of three grid items with auto-fit:

grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));

enter image description here

spec reference: https://www.w3.org/TR/css3-grid-layout/#auto-repeat