Easy Responsive Typography Using CSS clamp()

Working with responsive typography can get a bit complicated for some developers. There are various ways to make typography responsive, such as setting up font-size with viewport-unit, use media query, use CSS calc, etc.

But, did you know that CSS growing rapidly? Now, we can create responsive typography by only writing 1 line of CSS code!

CSS clamp() #

CSS clamp

I believe most of you are not familiar with this CSS function, but according to Caniuse, all major browser is already support it, so you can safely use it on production.

So, what is CSS clamp? #

Based on the article on MDN, The clamp CSS function clamps a value between an upper and lower bound. clamp enables selecting a middle value within a range of values between a defined minimum and maximum.

clamp takes three parameters: a minimum value, a preferred value, and a maximum allowed value, for example:

.clamp {
font-size: clamp(16px, 5vw, 36px);

clamp(MIN, VAL, MAX)

  • min is the minimum value
  • val is the preferred value
  • max is the maximum value

Lets breakdowns the code above. So, the value of .clamp is 5% of the viewport width because 5vw will resolve to 5% of the current viewport width, but it will not go higher than 36px or lower than 16px.

So, lets say your current viewport width is 1280px, the value of 5vw will be 64px, we get that from 1280 * 5%, but remember, we already set the maximum value to 36px, so the result of your current viewport width is 36px.

If you want to try it yourself, you can play around with this pen.

One more thing, you can use clamp with another properties such as padding, margin, height, etc. If you want to learn more about this superpower CSS function, you can go to https://developer.mozilla.org/en-US/docs/Web/CSS/clamp.