Use the CSS clamp() Function for Better Responsiveness

The CSS clamp() function clamps a value between an upper and lower bound. It enables selecting a middle value within a range of values between a defined minimum and maximum. So it takes three parameters: a minimum value, a preferred value, and a maximum allowed value. 1

What is the difference between the CSS clamp function and the CSS viewport width unit? First, they are the same at some points if you resize the window. But they are slightly different in some screen sizes. See the example below.

CSS clamp() Function Example

Take a look at this CSS code example with two h1 tag selectors and font-size property:

h1.first {
  font-size: clamp(2rem, 7vw, 4.5rem);
}

h1.second {
  font-size: 7vw;
}

The one with the clamp() function has a minimum and maximum value. When you resize the window, the font size will not be less than 2rem and more than 4.5rem.

The second selector font size with the viewport width unit will be smaller and larger as long as you resize the window without any limitations. See the below CodePen:

See the Pen CSS clamp() Function for Better Responsiveness by Alvand (@alvand1399) on CodePen.

Above, click on the EDIT ON CodePen at the top right corner. Then when opened, change the view to the right or left column from the top right. Now, resize the window to the lowest and highest possible amount.

CSS clamp() function prevents the headline font size from being too big on extra large screens and too small on extra small screens.

Conclusion

You can use this function with some other CSS properties like width. Think about how to use it in different situations. It will open some doors when coding your website. Click on this link to see A Useful JavaScript CSS Tool to Make Codes Readable or on this one if you want to know How to Have Splide Multiple Sliders on One Page.

References:

  1. https://developer.mozilla.org/en-US/docs/Web/CSS/clamp ↩︎

Published on:

Updated on:

Author:

Rate this post and help us improve our content to better serve you.

Help us spread the word! Click the share buttons below to share this post with your followers.

We’d love to hear your thoughts on this topic. Feel free to leave a comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *