This year, something interesting happened. A really cool CSS property got major browser support. If you have never heard of CSS Clamp, you are in for a treat. Get ready to learn something really cool. Here we go.

Before we get really into CSS Clamp, we must talk about min() and max().

Min() and Max()

These values do pretty much exactly what you think they would. They define the max and the min of anything you apply it to. The neat thing about the value is you can apply as many arguments to it as you want. If you wanted a width to be 50% of its parent and have a max-width of 600px you would typically do something like this:

div {
  width: 50%;
  max-width: 600px;
}

With min() we can do this with one simple line.

div {
  width: min(600px, 50%);
}

Example of both in action:

See the Pen Min CSS by Christopher Bishop (@cibgraphics) on CodePen.

The exact opposite can be done with CSS Max

Traditionally:

div {
  width: 75%;
  min-width: 400px;
}

and with CSS Max:

.width-max {
  width: max(400px, 75%);
}

See the Pen Max CSS by Christopher Bishop (@cibgraphics) on CodePen.

Truth is, you can add as many arguments as you want. One is perfectly valid, as is 10. Though having 10 arguments would be pretty hard to manage and tell what exactly is going on. Best to keep it only to what you need.

Clamp()

So what if you want to do both. What if you want to have a min-width of 320px, a max-width of 960px, and 90% width when it is not either of those widths?

Enter CSS Clamp. Here is the syntax

div {
  width: clamp(MIN, VAL, MAX);
}

With our example we can do something like:

div {
 width: clamp(320px, 90%, 960px);
}

Here it is working:

.width-traditional
  p width: clamp(320px, 90%, 960px);
div {
  background: #8ECD38;
  height: 40px;
  margin: 0 auto 20px;
  padding: 10px;
  display: flex;
  align-items: center;
  width: clamp(320px, 90%, 960px);
}

Browser Support

The good news here is that if you are willing to leave IE behind, you can start using this right away. It is fully supported in all the latest browsers. So use it and have fun.

For more information please look at some specs.