CSS: Reverse Clamp

/ 169

It may sound like a wrestling move, but it's a useful way to make sure your content is readable on mobile devices, without having to set up a bunch of media queries.


Sometimes the way text is rendered on mobile devices can lead to readability issues.

We have had CSS media queries for quite some time now, so we can use those to set up different font styling based on viewport size and even screen DPI. When using a mobile-first approach, we would typically use something like this:

html {    font-size: 16px; /* sets the base unit size for an REM unit */}p {    font-size: 1.5rem;}@media screen and (min-width: 640px) {    p {        font-size: 1rem;    }}

Which would give us a 0.5rem increase of font size on screens with less than 640px of width (so, a larger font on mobile devices)

This allows us granular control over our font size on any screen size we want to target, but, that is easier said than done at times, and managing breakpoints for a multitude of screen sizes for small projects is simply not something we want to spend time addressing.

Since early 2020 we've had wide browser support for the clamp function in CSS, which lets us calculate a value based on a minimum, base, and maximum value:

p {    /* Force the font-size to stay between 12px and 20px */    font-size: clamp(12px, 3vw, 20px);}

But, this only lets us make the font smaller on smaller screens, which sometimes is needed, but for content with a lot of text (i.e. the inner copy of an article) we might want to make the font larger on mobile devices.

calc() has entered the chat.

In order to make the font size bigger on smaller screens, we can use the calc function to subtract the value calculated with clamp from the base font size:

p {    font-size: calc(2.2rem - clamp(0rem, 3vw, 1.2rem));    line-height: 1.3em;}

With this code, our font size on larger screens is 1rem and it scales up to a maximum size of 2.2rem as the screen gets smaller, and using the em unit for the line-height allows the line-height to scale with the font size.

Awesome! You can see this in action here:

Read more about the clamp() function over on mdn web docs.