clamp() for Responsive Values

The Problem clamp() Solves

Before clamp(), making a value scale fluidly with the viewport - like a heading's font size - while still keeping sensible minimum and maximum limits meant writing several media queries with hardcoded breakpoints. clamp() does this in a single line.

The Three Arguments

h1 {
  font-size: clamp(1.75rem, 4vw + 1rem, 3rem);
}

clamp(MIN, PREFERRED, MAX) reads as: never smaller than the minimum, never larger than the maximum, and in between, scale fluidly according to the preferred value.

ArgumentRole
MinimumThe smallest the value is ever allowed to be
PreferredA flexible value (often using vw) that scales with viewport size
MaximumThe largest the value is ever allowed to be

Fluid Typography Without Media Queries

h1 { font-size: clamp(1.75rem, 4vw + 1rem, 3rem); }
h2 { font-size: clamp(1.375rem, 2.5vw + 1rem, 2rem); }

Text now scales smoothly as the browser window is resized, staying readable on small phones and appropriately large on wide desktop monitors, without a single breakpoint.

Uses Beyond Font Size

.container {
  width: clamp(300px, 90%, 1200px);
}

This keeps a container from ever becoming narrower than 300px or wider than 1200px, while otherwise flowing at 90% of the available width - a common pattern for a page's main content wrapper.

A Practical Tip

Combining clamp() with viewport units for the preferred value is what produces smooth scaling; using a fixed value there (like clamp(1rem, 1.5rem, 2rem)) has no real effect, since a fixed value never actually changes with viewport size.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.