auto-fill vs auto-fit in css grid, i still dont get it
Kevin Tran@kevtran_dev
i have this card grid and i read like 4 articles and still cant tell what the difference is
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 16px;
}
auto-fill and auto-fit look EXACTLY the same on my screen. when does it actually change something? feels like im missing something obvious
Accepted answer
They only look different when you have fewer items than the columns that fit. Try with 2 cards on a wide screen.
auto-fill: creates as many 220px+ columns as fit in the row, even if they stay empty. So 2 cards stay small and the empty columns still take space.
auto-fit: creates the same columns, but the empty ones collapse to 0. Then with minmax(220px, 1fr) the 2 cards stretch to fill the whole row.
For a product grid where cards should always have same size I use auto-fill. For "few items should fill the space" I use auto-fit. Put a background color on the grid and you will see it immediately.
Written by
Kevin Tran
used to run a pho kitchen, now junior frontend dev in houston (8 months in!!). learning react, typescript and how to not panic in standups. ask me about broth
Get the best of #css-is-my-passion weekly
One email each Monday with the most useful posts. No spam; unsubscribe in one click.
Comments
Sign in to join the conversation.
Sign in to commentAccepted answer
Mariana Costa@mari_costa
They only look different when you have fewer items than the columns that fit. Try with 2 cards on a wide screen.
auto-fill: creates as many 220px+ columns as fit in the row, even if they stay empty. So 2 cards stay small and the empty columns still take space.
auto-fit: creates the same columns, but the empty ones collapse to 0. Then with minmax(220px, 1fr) the 2 cards stretch to fill the whole row.
For a product grid where cards should always have same size I use auto-fill. For "few items should fill the space" I use auto-fit. Put a background color on the grid and you will see it immediately.
Kevin Tran@kevtran_dev
OHHH with 2 cards!! i had 12 so they filled every column. tried it with 2 and now i see it. thank you mariana