Experimenting with the CSS min() function

Week 200 was posted by Charanjit Chana on 2021-08-23.

Every time I see the definition of the min(), max() and clamp() functions, I feel like I understand their purpose but without using them in the real world it's something I have to revisit every time I'm interested in using them.

I thought it was worth taking a look as I see these functions coming up more and more but in all honesty it took me a while to wrap my head around how and why min() works. I think I have a way to explain it, but to me it's exactly how I would expect max() to behave (and vice-versa).

Explain CSS' min() function

When using the min() function, it takes two parameters. The size you want an item to be, followed by the maximum size it can be.

width: min(50vw, 800px);

In this example, the item will be 50vw wide until it hits 800px. All good and well, but 50vw of what exactly?

The important bit here is that the two properties work together to define this. At some point, 50vw and 800px are the same thing which is when the item will no longer grow in size. CSS will treat 1vw as 16px (800 / 50) which means that 100vw would be 1600px.

min() demo

I put a demo together over on Codepen which you should able to resize by dragging the bottom right corner. You'll need to drag it quite a bit to see the effect so it might be easier to click through and play with the size of your browser window to see it in action.

I need to play with these functions in the real world and I'll take a look at the max() function next. Along with grid and flexbox, CSS has become really complicated but in a really good way.

There's a great article by Urna Kravets on these three logical functions over on web.dev which is well worth a read with some excellent visualisations.

Tags: css, development

Tweet WhatsApp Keep Upvote Digg Tumblr Pin Blogger LinkedIn Skype LiveJournal Like