Dynamic font-size using only CSS3
It’s 2023 already, time flies! So using CSS media queries for different screen resolutions just to increase/decrease your text sizes for a couple pixels or rems is kinda annoying. Why don’t you use dynamic font-size instead?
What is dynamic font-size?
Dynamic font-size means your text sizes will be changed proportionally to the user’s viewport width. You just need to provide the minimum value of font-size, the maximum value of it, and two breakpoints, between which font will scale.
For example: let’s say you want your text to have a font size of 20px
at viewport width of 768px
and maximum size of 36px
when viewport width is 1920px
. But if the viewport width is less than 768px
, you don’t want your font-size to get lower than 16px
and if the viewport width is more than 1920px
you want your font size to stop scaling at 48px
.
Lots of words, better check the pictures below.
When viewport’s width is 768px
the font-size is equal to 20px
:
When viewport width is larger than 768px
the font-size scales proportionally:
At 1920px
it becomes 36px
:
For the screens smaller than 768px
, the font-size won’t be smaller than 16px
:
For the screens larger than 1920px
, the font-size won’t be bigger than 48px
:
Pretty cool, huh 😁?
What’s the trick?
To achieve that we only need one line of CSS:
font-size: clamp(16px, calc(20px + (36–20) * (100vw - 768px)/(1920–768)), 48px);
Here we use native CSS3 function clamp(), which accepts three arguments:
the minimum value, the desirable value and the maximum value. For the minimum value we use 16px
in the example above, the maximum value is 48px
.
The desirable value is the most tricky part — we use the CSS function calc() for it, which performs calculations between different CSS values.
20px (as well as 20)
— is our minimum value for the font-size;
36
— is the maximum value of the font-size;
768px (768)
— is the lower breakpoint;
1920
— the higher breakpoint;
100vw
returns the full width of the user’s viewport (1vw = 1%
of the viewport’s width).
To make sure this formula works let’s test it for our breakpoint values (which are 768px
and 1920px
).
So when the user’s viewport width becomes 768px
, then 100vw = 768px.
Just replace 100vw
to 768px
and you will get exactly 20px
(the right part of the formula equals 0px
).
Do the same with 1920px
viewport width and you will get exactly 36px
as the value for the font-size (the right part of the formula equals 16px
).
Demo
As you can see, dynamic font-size can be possible with only CSS3, thanks to clamp()
and calc()
functions. If you want to dive deeper into different solutions for dynamic font-size, I highly recommend this article to read:
https://css-tricks.com/linearly-scale-font-size-with-css-clamp-based-on-the-viewport/ .
Thanks for reading!
Stay safe and peace be with you!