Firefox Inspector showing the clamp() font-size rule for this website’s mobile paragraph text

How do you make a heading grow with the screen without becoming too small on a phone or enormous on a desktop? CSS has a useful feature called clamp().

It lets a value resize smoothly while setting a minimum and maximum. You can use it for font sizes, padding, margins and more.

Three values, one rule

The pattern is:

font-size: clamp(minimum, preferred, maximum);

For example, this is the rule used for the mobile heading on this website:

font-size: clamp(1.75rem, 7vw, 2.75rem);

Here is what each part means:

  • 1.75rem: the smallest permitted size—normally 28 pixels.
  • 7vw: the preferred size—7% of the viewport width.
  • 2.75rem: the largest permitted size—normally 44 pixels.

rem is based on the root font size of the page, commonly 16 pixels. vw means viewport width: 1vw equals 1% of the browser’s viewport width.

What happens on different screens?

Assuming a root font size of 16 pixels:

Viewport width Calculated size: 7vw Actual font size
320 pixels 22.4 pixels 28 pixels—the minimum applies
500 pixels 35 pixels 35 pixels
700 pixels 49 pixels 44 pixels—the maximum applies

The heading grows smoothly between its limits, without needing a separate rule for every screen size.

It works for spacing too

padding: clamp(16px, 4vw, 48px);

This creates padding that grows with the viewport, but never becomes smaller than 16 pixels or larger than 48 pixels.

A real example from this website

The screenshot shows the mobile paragraph styling in Firefox’s Inspector:

font-size: clamp(1rem, 3.8vw, 1.2rem);

With the usual 16-pixel root font size, the paragraph text scales between 16 and 19.2 pixels.

How does this fit with media queries?

clamp() controls the size. A media query controls when a rule applies.

@media (max-width: 767px) {  .example-heading {    font-size: clamp(1.75rem, 7vw, 2.75rem);  } }

In this example, the heading rule applies only when the viewport is 767 pixels wide or less. The class name is illustrative: replace it with the selector for your own heading.

A useful habit: test the result on narrow screens and with browser zoom. Fluid sizing should help people read your content comfortably.

Tags