Font size clamping calculation easily explained

If you've ever looked into how to make text size responsive without having to use media queries, you've probably come across something called clamp.

Unlike the responsiveness that comes from using media queries, which leads to abrupt changes in text size, clamp lets you set minimum and maximum values, and it takes care of smoothly adjusting the font size depending on the screen size where the text is displayed. This way, the text increases or decreases gradually and smoothly.

The idea behind clamp is awesome, but when you check out a real example to better understand how to use it, you might see something like this:

font-size: clamp(24px, 4vw, 48px)

The first and third parameters are pretty self-explanatory. The issue is with the one in the middle.

clamp(min, val, max)

When we check out the documentation, we find out that val is the expression that'll be used as long as its result is between the minimum and maximum values.

This is where things can get super confusing because if you multiply the viewport width by 4, you get a font size way bigger than the max value (48px). For the expression to return something between 24px and 48px, the viewport width would have to be between 6px and 12px, which makes no sense since no device has a viewport that narrow.

The confusion clears up once you realize that the number 4 doesn't represent an integer but a percentage. In practice, the notation is actually saying: 4% * vw.

Interpolating font size using the clamp function

Now things start to make sense. We'll get 24px on screens that are 600px wide or less, and 48px on screens that are 1200px or wider. For screens in between, the text size will increase or decrease smoothly as the screen width changes. For example, on a tablet in portrait mode, the text size will be around 30px (4% * 768px). If you rotate the tablet to landscape mode, you'll see the text size change to around 40px (4% * 1024px).

In this Gist, you'll find all the code you need to run locally the demo shown in this post. If you enjoyed this post and now fully understand how to use the clamp function, you might also be interested in learning how to use flexbox to make elements fill all the remaining space.