# clamp() Calculator

Handy little tool for calculating viewport-based clamped values.

Optional Stuff
Visual Example
• Root Size: 16px
• Clamped Size: 16–18px
• Current Size: 16px
• Viewport Size: 9001px

## How does this work? Permalink ¶

This calculator uses `rem` units which require knowing the font size at the document’s root. In most cases, that refers to the `html` element and this calculator is currently operating with a root font size of `16px`.

We need to figure out the rate of change: how much the size needs to change across a distance across the viewport. In other words, for every pixel of change across the viewport, how many pixels of change should there be in size? We can calculate this by dividing the difference in size by the difference in viewport.

``````Change = (sizeMax - sizeMin) / (viewportMax - viewportMin)
Change = (18px - 16px) / (1000px - 500px)
Change = 0.004``````

Next, let’s figure out what our preferred size should be (this is different from our minimum font size). We do this by asking how much change is applied to the size when the viewport is at its maximum size, and subtracting that from our desired size at the maximum viewport size.

``````A = sizeMax - viewportMax * Change
A = 18px - 1000px * 0.004
A = 14px = 0.875rem``````

The last piece of the puzzle is the most straightforward: we need to represent the rate of change as a value relative to the viewport, and we do so by multiplying the rate of change with `100vw`.

``````B = 100vw * Change
B = 100vw * 0.004
B = 0.4vw``````

Let’s put everything together with the `clamp()` function, otherwise our calculated value will be incorrect above and below our designated viewport bounds.

``````Result = clamp(sizeMin, A + B, sizeMax)
Result = clamp(1rem, 0.875rem + 0.4vw, 1.125rem)``````

We can perform a simple check that our calculations are correct by plugging in our minimum and maximum viewport values and seeing if they result in our desired minimum and maximum sizes.

Let’s not forget that viewport-based units (`vw`, `vh`, etc.) are kind of like a percentage, which we can factor into our calculations by dividing `B` by 100 when figuring out the true pixel-value result.

Note: Because of rounding, there may be some loss of accuracy around the 3rd decimal place in these calculations, but the browser will interpret them well.

``````A + B = 0.875rem + 0.4vw
A + B = 14px + 0.4vw

Minimum Size ≈ 14px + (0.004 * 500px)
Minimum Size ≈ 14px + 2px
Minimum Size ≈ 16px

Maximum Size ≈ 14px + (0.004 * 1000px)
Maximum Size ≈ 14px + 4px
Maximum Size ≈ 18px``````

Wondering why we don’t need `calc()` around the middle value of the `clamp()` function? Michelle Barker’s got you covered with this quick tip, and check out `clamp()` on MDN to learn more.