min(), max(), and clamp() are CSS magic!

Avatar of Chris Coyier
Chris Coyier on

Nice video from Kevin Powell. Here are some notes, thoughts, and stuff I learned while watching it. Right when they came out, I was mostly obsessed with font-size usage, but they are just functions, so they can be used anywhere you’d use a number, like a length.

Sometimes pretty basic usage allows for tighter code, but the change to get there feels a little mind-bending. Like how to set a “max” here, you really use min().

.el {
  width: 75%;
  max-width: 600px;

  /* tighter, but the change from max to min feels weird */
  width: min(75%, 600px);
}

The min() and max() functions can take more than two values, which is cool, but hard to keep straight what is going on! It would be nice if DevTools could tell you which one it picked at any given time.

.el {
  width: min(100px, 25%, 50vh, 30ch);
}

You don’t need a calc() to do math inside!

.el {
  width: min(10vw + 10%, 100px);
}

It’s reasonable you’d want to be setting a min and max value. You can nest the functions to do this, but it’s less mind-bendy to do with clamp().

.el {
  /* Note we're always using a relative unit somewhere
     so that zooming stays effective. */
  font-size: clamp(0.9rem, 1vw + 1rem, 2.2rem);
}

Here’s the video embedded:

Direct Link →