Responsive font size using only CSS
There are many ways to do responsive text on the web. Many using javascript for example.
But did you know it is possible to do with just CSS?
The easiest way to do it is to use units like vw
or vh
instead of px
.
CSS has many length units.
These are “viewport relative units”:
vw
is equal to 1% of the width of the viewportvh
is equal to 1% of the height of the viewport
2vw
5vw
That works but as you can see the results are a bit wild. And it’s hard to get actually good results.
It could be improved by using the vmin
and vmax
units which correspond to the smaller or larger of vw
and vh
.
We can improve this by combining it with a base px
value instead of using the vw
directly.
This is done with the calc()
function, which lets you perform calculations.
calc(10px + 1.0vw)
calc(25px + 0.2vw)
It’s getting better but it would be nice to put some limits on that, because it may become too small on very small screens or gigantic on large displays. This could be solved using media queries but that means adding a lot more code, altough in certain occasions this may be the way to do it.
But if we just want to limit the font size we can use the min
,max
and clamp
functions.
This way we can constrain the font size between, for example, a minimum of 15px
and a maximum of 60px
.
clamp(15px, calc(10px + 2vw), 60px)
clamp(25px, calc(10px + 2vw), 45px)
And it should work in all common browsers! (Source: Can I use?).