🎁 Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Making CSS responsive with the clamp, min and max functions

The clamp, min, max functions are a trio of CSS functions that can make our life easier when working with a responsive design. They make sure the increase or decrease in size never goes beyond some limits.

Let's start with the clamp function. It takes three parameters:

  • the minimal value
  • the preferred size
  • the maximum size

So, for example, if we say:

.my-element {
    width: clamp(300px, 50%, 800px)
}

Then .my-element will try to be always 50% of its parent's width, but will never go under 300px or more that 800px.

It can be very useful when working with font sizes. In a responsive context, it's great to be able to use the viewport units with font sizes. This will mean that when our screen is getting smaller also our font size will decrease. But the font can become too small to read on small screens.

So, the clamp() function to the rescue! We can use a statement like the one below to make sure our font size will always be readable and also responsive.

.my-resposive-readable-text {
    font-size: clamp(12px, 3vw, 24px);
}

By the way, I’ve also written this article on how to implement the clamp number function in Javascript.

Alongside with clamp(), we have two other complementary functions.

The CSS min() function will take two parameters are will return the smaller one to be used as a size.

So, if we have:

.widget {
    width: min(20rem, 80%)
}

Then the .widget component will be the smallest of the two values from 80% of its parent or 20rem.

The max() function will behave the same, just that it will select the biggest value.

One nice thing about all of these functions is that you don’t need a calc() function to do math inside.

We can just write max(20vw - 1rem, 10% + 40px) and it will work. Just be sure to leave an empty space before and after the operator sign.

Of course, all the time when we use the min() or max() functions we will need to use different units types. Writing something like min(10%, 25%) it's nonsense as 10% will always be the smaller value.

Kevin Powel has a nice video explaining more about these functions:

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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