minmax()
Example
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, 300px);
}.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr));
}Columns now stretch to fill the row, and min() stops a column from overflowing screens narrower than '300px'.
Common mistakes
- A grid column overflows because
1frhas an automatic minimum of the content width. - Cards overflow narrow screens because the
minmax()minimum is wider than the viewport.
Key points
- Flexible columns that hold long content use
minmax(0, 1fr)instead of1fr. - Responsive card grids use
repeat(auto-fill, minmax(200px, 1fr))instead of media queries for each column count. fris not used as the minimum value, which is invalid.
Interview questions
What is the difference between auto-fill and auto-fit with minmax()?
auto-fill keeps empty tracks when items run out. auto-fit collapses them, so the items stretch to fill the row.
Why does 1fr not shrink below the content width?
1fr means minmax(auto, 1fr), so the minimum is the content size. Use minmax(0, 1fr) to let it shrink.
Can I use minmax() in flexbox?
No. minmax() only works in grid track sizes like grid-template-columns and grid-auto-rows.