Simple Responsive Text Sizing in CSS
Posted on • Last updated on
Using the min, max, and clamp functions in CSS is a great way to implement fluid typography that works on all screen sizes!
The Problem
You may have attempted to create responsive font sizing by using percentage units, which can lead to problems if a user has an extra small or widescreen, wherein the font will become comically small or large. Or maybe you’ve tried using Media Queries to achieve responsive font sizes, which can be annoying to use. These problems are the main reason why I like to use the min, max, and clamp functions to easily make responsive text.
Max Font Size
It's a bit counterintuitive, but if you only want to set a maximum font size, you can use the min function.
min(x, y)
If you want your font to be 5% of the view width but have a maximum size of 100px, you can do the following:
font-size: min(5vw, 100px)
Try it out:
Responsive
Min Font Size
To set a minimum font size, you can use the max function.
Suppose you want the font size to be 5vw, but only if 5vw is above 10px. To achieve this, you can do the following:
font-size: max(5vw, 10px)
When the viewport width is such that 5vw exceeds 10 pixels, the font size will be 5vw. However, if 5vw is 9 pixels or less, CSS will choose the larger value, which is 10 pixels, effectively setting a floor for the font size.
Try it out:
Responsive
Max and Min Font Size
Many times, especially when setting font sizes, you want to set both a minimum and maximum size. This is what clamp() is for!
clamp(min, suggested, max)
The clamp function combines the powers of min() and max() by setting a flexible range within which an element can adjust. With clamp(), you can define the minimum, suggested, and maximum sizes, allowing for truly responsive design that adapts to any screen.
Example:
font-size: clamp(10px, 5vw, 30px);
The above example tries to set the font size to 5% of the screen's width, but after 5vw is less than 10px, the function returns the minimum value, and once 5vw is greater than 30px, the maximum value is returned.
Try it out:
Responsive
Conclusion
These three functions are a great way to set boundaries on font sizes. Beyond fluid typography, they are also a great way to make other parts of your website more responsive!