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-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 thefont-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.