DEV Community

Cover image for Improving site responsiveness with CSS clamp() function

Improving site responsiveness with CSS clamp() function

Abdessamad Bensaad
Look at the Flowers
・2 min read

To improve the responsiveness of your site, you don't have to use some complex event listeners using the Web API ResizeObserver, calc() function, or CSS media queries that will substitute the required page elements depending on the browser window size.

Clamp() is the only function specifically designed to allow almost any element to adjust its size within certain limits to fit the application window.


clamp(MIN, VALUE, MAX) is calculated as clamp will return the value specified by the second argument (preferred) if it is within the minimum and maximum values. Computed values ​​can be passed as any of the arguments.max(MIN, min(VALUE, MAX))

An example of using the clamp function to improve the responsiveness of the image size


The following units can be used for the preferred value:

  • The width of the viewport in% if clamp is used in the body (or the width of the container containing the clamp).
  • em is the font size in the current context.
  • rem is the font size in the context of the HTML element.
  • vw - 1% of the window width.
  • vh - 1% of the window height.

Supported browsers

Clamp is not supported in Internet Explorer only.

Clamp supported browsers

Where to use

Headers font

A great use case for clamp () is in headers. Let's say you want a header with a minimum size of 16 pixels and a maximum size of 50 pixels. The clamp () function will give us an intermediate value that does not go beyond the specified limits.

.title {
  font-size: clamp(16px, 5vw, 50px);
Enter fullscreen mode Exit fullscreen mode

Clamp () is ideal here because it ensures that the font size used is easy to read. If you use min () to set the maximum font size, then you won't be able to control the font on small screens.

CSS Grid - Responsive Grid

Alt Text

Another good example is the responsive CSS grid column spacing for mobile screens. With clamp, this is pretty straightforward to implement.

.wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-gap: clamp(1rem, 2vw, 24px);
Enter fullscreen mode Exit fullscreen mode

Adaptive padding for sections

Example padding for sections

Clamp () is also ideal for setting the minimum and maximum spacing between sections. This can be done with the following CSS:

.section {
  padding: clamp(2rem, 10vmax, 10rem) 1rem;
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

oenonono profile image

"When people zoom a page, it is typically because they want the text to be bigger. When we anchor the text to the viewport size, even with a (fractional) multiplier, we can take away their ability to do that. It can be as much a barrier as disabling zoom. If a user cannot get the text to 200% of the original size, you may also be looking at a WCAG 1.4.4 Resize text (AA) problem"