12
Am I the only one who just realized CSS math functions can replace entire calc() blocks?
I was messing with a responsive grid layout yesterday and kept running into this wall where I needed to mix fixed and fluid units. I was about to write some stupid long calc() expression like calc(100% / 3 - 10px) for the third time when I realized clamp() and min() and max() exist. Found this article on MDN that broke down how you can nest them together and it blew my mind. For example, instead of a media query to cap a font size, you can just do clamp(1rem, 2.5vw, 2rem) and it handles everything. I tested it on a card grid for a portfolio site I'm building and it cut my layout CSS by like 40%. Has anyone else found a specific use case where min() or max() saved you from writing extra media queries?
2 comments
Log in to join the discussion
Log In2 Comments
roberts.diana6d ago
oh man i saw that exact same MDN article and honestly people are acting like this is some kind of magic trick lol. clamp() is cool and all but its not gonna save you from having to actually think about your layout. i tried swapping out my media queries on a project last week and ended up with some weird overflow issues cause i was nesting min() inside max() wrong. the whole "cut my CSS by 40%" thing sounds like you were writing bad css to begin with tbh. like yeah its nice to replace one or two queries but if youre just slapping clamp() on everything youre gonna run into edge cases where your font size looks fine on desktop and then at tablet size its all over the place. maybe its just me but i still reach for a good old media query when i need something bulletproof.
5
wendy_clark6d agoMost Upvoted
Jumped into this same rabbit hole last month and ended up spending two days debugging a layout that looked perfect on my 27-inch monitor but turned into a mess on my phone. Turns out I had clamp() in a flex item and forgot to account for the parent container changing width at different breakpoints. Still, I do like how clean the code looks now even if it took forever to figure out. Are you still relying on media queries for most of your projects or do you mix it up with these newer functions?
3