Today I Learned

CSS clamp()

To put it simply, CSS's clamp() function lets you define THREE values for a single property:

  • A minimum value
  • A preferred value
  • A maximum value

"That's pretty cool Connor, but... when would I even use it?"

There are a lot of use cases where clamp() comes in really handy, but where I use it the most is when handling my flexible typography.

You might be tempted to use classic media queries to sort out your responsive typography, like so:

h1 {
  font-size: 100%;
}

@media (min-width: 400px) {
  h1 {
    font-size: 40px;
  }
}

@media (min-width: 640px) {
  h1 {
    font-size: 64px;
  }
}

But with clamp(), you could do it all in a one-liner:

h1 {
  font-size: clamp(40px, 10vw, 64px);
}

Now, under the hood, the CSS is thinking like so:

  • If 10vw > 64px, font size should be 64px.
  • If 10vw > 64px AND < 40px, font size should equal 10vw (e.g. when the viewport is 500px wide, the font size will be 50px).
  • If 10vw < 40px, font size should be 40px.

Pretty cool, right? It's not useful for font sizes either - I use it for so many different CSS properties (width, height, margin, padding...) that I've lost track. It's a powerful tool to have in your back pocket, that's for sure.


Official docs: MDN CSS clamp() Function


Back to TIL

Let's grow your business,
together

Whether you're after dev work on a brand new site, an updated design, or just have a great business idea you want to get the ball rolling on, I'm here to help. Let's collaborate together!

Start a project