DEV Community

Stephen Farrugia
Stephen Farrugia

Posted on • Updated on

CSS Grid minmax behaviour quirk

I have two versions of a grid column template:

Version A is:
grid-template-columns: repeat(auto-fit, minmax(300px, auto))

Version B is:
grid-template-columns: repeat(auto-fit, minmax(300px, 600px))

Codepen: https://codepen.io/stevesydney/pen/xxmbNav

Version A behaves as expected by stretching columns to fill space until there is a minimum of 300px to add an extra column.

But version B defaults to the maximum 600px column width and adds columns when there is space for another 600px one. It only shrinks the column width when there is space for a single one.

Why does adding an absolute max value in the minmax() switch this behaviour? Is there a way to make it behave the same as Version A with the 600px width constraint?

EDIT: Updated Codepen with a Version C solution (kind of)

https://codepen.io/stevesydney/pen/xxmbNav

EDIT 2: Even better solution that uses less code and produces a cleaner, more fluid, result. Check out Version E

https://codepen.io/stevesydney/pen/xxmbNav

Top comments (6)

Collapse
 
dev_michael profile image
Michael Amachree

Hey, addressing your question about adding an absolute maximum value in the minmax() function – this tweak shifts how things work because it sets a firm upper limit on column width. In Version B, the columns start at 600px and only contract if there's room for just one. To get Version B to act like Version A with a 600px cap, try this: use grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)). That way, columns can stretch to 600px when possible, while still adapting to smaller screens. Check out this link: codepen.io/michael-obubelebra-amac...

Collapse
 
fasterandworse profile image
Stephen Farrugia

Thank you for your reply. I have updated the codepen with the solution I've come up with for the time being

codepen.io/stevesydney/pen/xxmbNav

Collapse
 
afif profile image
Temani Afif • Edited

minmax() will always try to use the max value when it's possible so if your max value is a fixed value then it will be used. It won't try to create as many column as possible.

Collapse
 
fasterandworse profile image
Stephen Farrugia

yes, it's interesting behaviour if the max value is less than the equivalent of the (min value x 2 ) + column gap. Otherwise the min value is ignored until the viewport is smaller than the max width of a single column.

Collapse
 
dev_michael profile image
Michael Amachree

Absolutely, and here's the cool part: if the space you're looking at is larger than the widest single column, the smallest value takes a bit of a back seat. All these combinations add a touch of complexity to how things unfold! 😊

Thread Thread
 
fasterandworse profile image
Stephen Farrugia

FYI we have found a workable solution! See Example E for how well it behaves regardless of having one item, two items, or many items codepen.io/stevesydney/pen/xxmbNav