Responsive Grid Auto-fit with defined Columns
Don't know if this has been done before but cool hack i did when working on a website:
https://codepen.io/K_ellvyn/pen/WNqjrvm
5 Replies
KPow has a couple videos showing this pattern. I think you need to account for more of the gap though , if you have four cols you’ll need
Then subtract that value instead of just one instance of gap ? I just skimmed your codepen so maybe you have that calculation somewhere but anyway here’s one relevant KPows videos (there’s another one I cannot find that I think will be helpful Grrr), timestamp 9:30
Kevin Powell
YouTube
Use this instead of media queries or container queries
Media queries are a bit limited in how they work, and while container queries go a really long way in solving a lot of those limitations, there are intrinsic patterns that we can follow that allow us to do things that neither one of them can do.
The setup is a bit strange and can look complex, but, in my opinion, it's also 100% worth it!
🔗 Lin...
hm
i saw his videos covering grid auto-fit but the problem i encountered was that once an grid child hit its 'min' threshold in a minmax function it wouldn't shrink more
so i came up with that
also how come youre subtracting one from the column count then multiplying the base gap?
Because you don't just have one gap if you have 4 columns. You have 3 , a gap in-between col1 & col2, gap bw col2 & col3 , gap bw col3 & col4. You'll have one less gap as you have columns so if you have 6 cols, you have 5 gaps, 8cols 7 gaps, 10 cols 9 gaps, etc. You want to account for all those gaps not just one to calculate the breakpoint.
I love the min() function it's one of my favourite things in css I think. Makes responsiveness soo much easier. You do need a fixed value , not necessarily pixels but has to be rems, ch, px, ex etc something fixed to use
min(100%, 40ch)
oh right just saw the video
the way i did it was i passed down the width of the container and divided that by the number of columns
and then subtracted that by the gap
figured that there was gonna be a fixed width in the equation anyways so might as well just divide the container
i think my solution is good if multiple breakpoints are needed for a grid
and kps solution would work as a media query hack
It's nice to just have it break at the right time without adding any media queries if you calculate where those breakpoints should be. There's a name for this hack but I forget what it is. Something like the Holy Grail