Handy little tool for calculating viewport-based clamped values.
Minimum Font Size (px) Maximum Font Size (px) Minimum Viewport Width (px) Maximum Viewport Width (px) The Result
- Root: 16px
- Clamped: 16–18px
How does this work?
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.1. We need to figure out the rate of change: how much the font size needs to change across a distance of viewport width. In other words, for every pixel of change in viewport width, how many pixels of change should there be in font size? We can calculate this by dividing the difference in font size by the difference in viewport width.
Change = (fontSizeMax - fontSizeMin) / (viewportMax - viewportMin) Change = (18px - 16px) / (1000px - 500px) Change = 0.004
2. Next, let’s figure out what our starting font size should be (this is different from our minimum font size). We do this by asking how much change is applied to the font size when the viewport is at its maximum width, and subtracting that from our desired font size at the maximum viewport width.
A = fontSizeMax - viewportMax * X A = 18px - 1000px * 0.004 A = 14px = 0.875rem
3. 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 * X B = 100vw * 0.004 B = 0.4vw
4. 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(fontSizeMin, A + B, fontSizeMax) Result = clamp(1rem, 0.875rem + 0.4vw, 1.125rem)
Learn more
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.Shoutout to James Gilyead and Trys Mudford for building Utopia—a fully-fledged tool for calculating fluid type, space, and grids for your design systems—and first introducing me to this amazing technique!