CSS clamp() Function

The clamp() function lets you constrain a value between a defined minimum and maximum.

It takes three comma-separated arguments: a minimum value, a preferred value, and a maximum value. The browser will use the preferred value as long as it sits between the minimum and maximum. If the preferred value drops below the minimum, the browser uses the minimum. If it exceeds the maximum, the browser caps it at the maximum.

This function is a game-changer for responsive design. Instead of writing half a dozen media queries to adjust font sizes, widths, or padding for different screen sizes, you can use a single clamp() rule to let the browser handle the scaling smoothly.

One of the most popular use cases is fluid typography. In the example below, the font size will grow and shrink based on the viewport width (vw), but it will never get smaller than 1.5rem and never get larger than 3rem. Try resizing your browser window to see it in action:

View Output Full Screen Preview

Responsive Widths

Another excellent use case for clamp() is controlling the width of a container. You often want a container to take up a percentage of the screen, but you don't want it to get too squished on mobile devices or too stretched out on ultra-wide monitors.

By using clamp(), you can set a fluid percentage width while enforcing strict pixel boundaries. Here's an example where the box wants to be 50% of its parent's width, but it's clamped between 250px and 600px:

View Output Full Screen Preview

How It Works Under the Hood

If you're familiar with the min() and max() functions, clamp() is actually just a convenient shorthand for combining them.

Writing clamp(MIN, VAL, MAX) is mathematically identical to writing max(MIN, min(VAL, MAX)). The clamp() syntax is just much easier to read and write.

Also, just like the calc() function, you can perform math directly inside any of the three arguments without needing to nest additional calc() functions (e.g., clamp(1rem, 2vw + 1rem, 3rem)).

Official Syntax

The official syntax of the clamp() function is as follows:

Possible Values

As indicated in the official syntax, the clamp() function accepts three values in a specific order:

Minimum Value

The absolute smallest value allowed. If the preferred value is less than this, the minimum value is used.

Preferred Value

The dynamic value you want to use (typically a percentage, viewport unit, or a calculation). This value will be used as long as it falls between the minimum and maximum.

Maximum Value

The absolute largest value allowed. If the preferred value is greater than this, the maximum value is used.

CSS Specifications

Browser Support

The following table provided by Caniuse.com shows the level of browser support for this feature.