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
Top comments (6)
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: usegrid-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...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
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.
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.
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! 😊
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