Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save benjaminblack/865553e33737eda3253beac783903de7 to your computer and use it in GitHub Desktop.
Save benjaminblack/865553e33737eda3253beac783903de7 to your computer and use it in GitHub Desktop.
Linear interpolation of font size based on viewport dimensions using viewport units

If a font size should scale linearly with the viewport width (or height), e.g. from 12px at 375w to 24px at 1280w, the interpolated font size can be calculated using the slope-intercept line equation (y = mx + b) with x set to 100vw (or vh) and using px units for b.

Make your life easier by using Wolfram Alpha to compute the equation of the line passing through two points (x1, y1) and (x2, y2), where x1 and x2 are the size of the viewport dimension (width or height) and y1 and y2 are the target font sizes at those viewport dimensions.

Continuing the example above, for 12px at 375w to 24px at 1280w, the points are (375,12) and (1280,24).

For the line between those two points, Wolfram Alpha returns the equation:

y = (12/905)x + (1272/181)

Written as a CSS rule, this is:

font-size: calc((12/905) * 100vw + (1272/181) * 1px)

This works because 100vw is exactly 100% of the viewport width, even as the viewport width varies. Thus, when the viewport is 375w, then 100vw equals 375px. Likewise, when the viewport is 1280w, then 100vw equals 1280px.

Checking the result at the two viewport sizes (375 and 1280):

(12/905) * 375 + 1272/181 = 12
(12/905) * 1280 + 1272/181 = 24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment