Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of 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 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);

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:

Home Screencasts Best of Newsletter Search X