How to make a responsive font size
Short answer
clamp() sets a minimum, a preferred value and a maximum. Change the window width:
<h1 style="font-size: clamp(1.5rem, 1rem + 4vw, 3rem); margin: 0;">Fresh coffee every day</h1>The heading is never smaller than 1.5rem on a phone or larger than 3rem on a big monitor, and in between it grows smoothly with the window width.
Why rem + vw
If you write only 4vw, the size depends entirely on the window and stops responding to page zoom — bad for people who enlarge text. Adding 1rem keeps the link with the browser settings.
A scale for all headings
It is handy to set up variables and use them across the site:
:root {
--step-1: clamp(1.1rem, 1rem + 0.5vw, 1.3rem);
--step-2: clamp(1.4rem, 1.1rem + 1.5vw, 2rem);
}
h2 { font-size: var(--step-2); }
h3 { font-size: var(--step-1); }Common mistake
People make body text fluid with vw too, and it becomes huge on a wide monitor and tiny on a phone. For paragraphs a constant 1rem is usually enough; keep clamp() for headings.
Functions used in this recipe
- clamp() — Keeps a value within limits: the preferred value, but not less than the minimum and not more than the maximum.
- font-size — The size of the font.
- px, em, rem, %, vw, vh — Units for lengths in CSS: absolute pixels and relative units.