Traditional responsive web design relies on "stepping" font sizes at specific breakpoints (e.g., font-size: 16px on mobile, font-size: 20px on desktop). Fluid Typography removes these jagged jumps by allowing the font size to scale linearly between a minimum and maximum value based on the viewport width (vw). The Math Behind the Fluidity The core of this implementation is the CSS clamp() function. It takes three parameters:
- Minimum Value: The smallest the font can get (e.g., mobile).
- Preferred Value: A dynamic unit (usually vw) that scales with the screen.
- Maximum Value: The upper limit (e.g., large desktops).
A robust, production-ready implementation of fluid text elements using CSS clamp(). This approach ensures accessibility and eliminates the need for excessive media queries.
To create a fluid scale, we use a central CSS variable for the "ideal" scaling factor.
:root {
/* Formula: clamp(min, preferred, max)
We use a mix of rem and vw to ensure accessibility (zooming still works).
*/
--font-size-base: clamp(1rem, 0.95rem + 0.25vw, 1.25rem);
--font-size-h1: clamp(2rem, 1.5rem + 2.5vw, 4rem);
--font-size-h2: clamp(1.5rem, 1.2rem + 1.5vw, 2.5rem);
}
body {
font-size: var(--font-size-base);
line-height: 1.6;
}
h1 {
font-size: var(--font-size-h1);
line-height: 1.1;
font-weight: 800;
}If you set font-size: 5vw, the text will scale, but it ignores the user's browser settings. By adding a rem value (e.g., 0.95rem + 0.25vw), we ensure that if a user increases their default font size for accessibility, the fluid text respects that preference.