Week 215 was posted by Charanjit Chana on 2021-12-06.
Having finally got my head around the CSS min() and max() functions, time to dive into figuring out the clamp() function. It's one I've seen mentioned a few times, specifically around responsive typography so it's been on my radar for a while.
Turns out it's pretty simple but I've not found the description that works for me, only through experimenting have I come to understand it.
Rather than starting with typography let's work out an example using an image. With the following example, the image would be at least 200px, ideally 20vw and at most 300px.
width: clamp(200px, 20vw, 300px);
While the minmax() function will try to keep it to the minimum size and ensure it's no bigger than the maximum, clamp() works a little differently where it tries to be as big as possible, but no smaller than the minimum. Looking back, my article on minmax() was useful for it's description but nothing more than that. I need to look into it some more to ensure I understand it correctly.
Back to clamp() and now we can look into responsive typography. The premise is similar, but using the vw value for font-sizing feels odd to me. Mostly because I'm still a beginner when it comes to typography and sizing so translating vws to ems or rems (or even pixels) is a little foreign to me.
font-size: clamp(2rem, 2vw, 5rem);
The value for font-size will be at least 2rem and at most 5rem but in between feels like magic at the moment. If 2vw equates to a value in between the min and max it will be that instead. The maths is a bit weird here for me... Perhaps an example with pixels will be easier to explain?
font-size: clamp(16px, 5vw, 40px);
So it's clear to me that the minimum size will be 16px, the max will be 40px and in between it will be 5vw. You need to take the max value and begin calculating from there. In this example, 1vw would equal 8px (40px / 5vw) which would make 100vw would be 800px. If you were to resize the window, then above 800px in width, you'd see nothing larger than 40px and below 320px (1vw = 3.2px) it will be no smaller than 16px in size.
So back to the original example with rems. Here, 1vw would equate to 2.5rems and the top viewport size would be 250rems, and 100rems at least. You can play with the example below over on Codepen and see how clamp works.
Tags: css, development