{"id":299523,"date":"2019-11-29T08:11:40","date_gmt":"2019-11-29T15:11:40","guid":{"rendered":"https:\/\/css-tricks.com\/?p=299523"},"modified":"2020-05-19T05:47:39","modified_gmt":"2020-05-19T12:47:39","slug":"simplified-fluid-typography","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/simplified-fluid-typography\/","title":{"rendered":"Simplified Fluid Typography"},"content":{"rendered":"\n

Fluid typography is the idea that font-size<\/code> (and perhaps other attributes of type, like line-height<\/code>) change depending on the screen size (or perhaps container queries if we had them).<\/p>\n\n\n\n

The core trickery comes from viewport units<\/a>. You can literally set type in viewport units (e.g. font-size: 4vw<\/code>), but the fluctuations in size are so extreme that it’s usually undesirable. That’s tempered by doing something like font-size: calc(16px + 1vw)<\/code>. But while we’re getting fancy with calculations anyway, the most common implementation ended up being an equation to calculate plain English:<\/p>\n\n\n\n

I want the type to go between being 16px on a 320px screen to 22px on a 1000px screen.<\/p><\/blockquote>\n\n\n\n\n\n\n\n

Which ended up like this<\/a>:<\/p>\n\n\n\n

html {\n  font-size: 16px;\n}\n@media screen and (min-width: 320px) {\n  html {\n    font-size: calc(16px + 6 * ((100vw - 320px) \/ 680));\n  }\n}\n@media screen and (min-width: 1000px) {\n  html {\n    font-size: 22px;\n  }\n} <\/code><\/pre>\n\n\n\n

That’s essentially setting a minimum<\/strong> and maximum<\/strong> font size so the type won’t shrink or grow to anything too extreme. “CSS locks”<\/a> was a term coined by Tim Brown.<\/p>\n\n\n\n

Minimum<\/strong> and maximum<\/strong> you say?! Well it so happens that functions for these have made their way into the CSS spec<\/a> in the form of min()<\/code> and max()<\/code>.<\/p>\n\n\n\n

So we can simplify our fancy setup above with a one-liner and maintain the locks:<\/p>\n\n\n\n

html {\n  font-size: min(max(1rem, 4vw), 22px);\n}<\/code><\/pre>\n\n\n\n
body {\n  font-size: clamp(100%, 1rem + 2vw, 24px);\n} <\/code><\/pre>\n\n\n\n

That’ll be Chrome 79+ (which doesn’t hasn’t shipped<\/a> to stable but will very soon).<\/p>\n\n\n\n

Uncle Dave is very happy that FitText<\/a> is now a few bytes instead of all-of-jQuery plus 40 more lines. Here is Dave chucking CSS custom properties at it:<\/p>\n\n\n\n