Auto-fit Vs Auto-fill
Auto-fit Vs Auto-fill
When we use the CSS Grid
grid layout, we often use the minmax()
function. When using the minmax()
function, it is very important to decide whether to use the auto-fit
or auto-fill
keyword. If used improperly, it may lead to unexpected consequences.
When using the minmax()
function:
auto-fit
: The grid item will be expanded to fill the available space.auto-fill
: The available space will be reserved without changing the width of the grid item.
Nevertheless, using auto-fit
can cause grid items to be too wide, especially if they are smaller than expected. See the following example.
.wrapper {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
grid-gap: 1rem;
}
If there is only one grid item and auto-fit
is used, the item will expand to fill the container width.
Four sub-items:
A child:
In most cases, such behavior is not desired. So in my opinion, it is better to use auto-fill
.
Four sub-items:
A child:
Example
.wrapper {
--sizing: auto-fit;
display: grid;
grid-template-columns: repeat(var(--sizing), minmax(100px, 1fr));
grid-gap: 1rem;
}
auto-fit-fill
Adjust the container size to see the effect