📓 Cabinet of Ideas

A Formula for Responsive Font Size

A formula for responsive font-size #

Excerpt #

This CSS is now part of most websites I make:


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-sizeLarge font-sizeBreakpoint
Medium.com1.125rem1.25rem728px
Substack.com1.125rem1.25rem768px
Nytimes.com1.125rem1.25rem740px

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.

More by Jim #

Tagged #programming, #web. All content copyright James Fisher 2024. This post is not associated with my employer. Found an error? Edit this page.