Fluid Font Size with clamp() in CSS
Hey there! When building a responsive UI, you often set your elements to respond to the screen or container size automatically using percentages, a minimum width, and/or a maximum width. I’m sure you’ve also wanted to do the same with your font sizes at some point. Well, that’s completely possible with the clamp()
function in CSS.
In this short guide, we’ll take a look at how to use the clamp()
function to create a fluid font size that adjusts smoothly.
In CSS, the clamp()
function allows you to specify a minimum and maximum font size, and a preferred font size.
Here’s an example:
h1 {
font-size: clamp(24px, 4vw, 36px);
}
In this example, the clamp()
function takes three values:
- The minimum font size (24px).
- The preferred font size (4vw).
- The maximum font size (36px).
The h1
element will have a minimum font size of 24px, a maximum font size of 36px, and a preferred font size of 4% of the viewport width (4vw). This means that the font size will scale up or down depending on the size of the viewport, but will never be smaller than 24px or larger than 36px.
Here’s another example, where the font size of a paragraph element is set to scale between 18px and…