A formula for responsive font-size

This CSS is now part of most websites I make:

:root {
  font-size: calc(1rem + 0.25vw);

This rule is an alternative to @media rules like this from nytimes.com:

p { font-size: 1.125rem; }
@media (min-width: 740px) {
p { font-size: 1.25rem; }

This pattern is the norm: a small font size, a large font size, and a breakpoint. Here’s a sample of common sites:

Small font-size Large font-size Breakpoint
Medium.com 1.125rem 1.25rem 728px
Substack.com 1.125rem 1.25rem 768px
Nytimes.com 1.125rem 1.25rem 740px

But breakpoints are mathematically ugly! Instead of defining font-size piecewise, can’t we use one linear function? Here’s the line I believe they’re trying to approximate:

With modern CSS, we can just write that function! It’s calc(1.0625rem + 0.2604vw). I round this to 1rem + 0.25vw.

Sharp-eyed readers might wonder: doesn’t my CSS have circular reasoning? If rem is defined as “Font size of the root element”, how can we use 1rem in the definition of font-size on the root element?! It turns out it’s a special case:

When specified in the font-size property of the root element, or in a document with no root element, 1rem is equal to the initial value of the font-size property.

Discussion on Hacker News.
Tagged #programming, #web.
👋 I'm Jim, a full-stack product engineer. Want to build an amazing product and a profitable business? Read more about me or Get in touch!

More by Jim

This page copyright James Fisher 2024. Content is not associated with my employer. Found an error? Edit this page.