Course outline · 0% complete

0/30 lessons0%

Course overview →

Fluid sizing with clamp

lesson 7-3 · ~8 min · 23/30

clamp(): fluid with guardrails

Breakpoints jump: a headline that is 32px at 767px wide and 56px at 768px looks broken mid-resize, and covering every width with queries means writing a dozen of them. Sometimes you want sizes to glide. clamp(min, preferred, max) keeps a value near its preferred size but never past the guardrails:

h1 {
  font-size: clamp(2rem, 5vw, 3.5rem);
}
.content {
  width: clamp(320px, 90%, 60rem);
}

The h1 wants to be 5% of the viewport width (vw, lesson 5-3), so it grows as the window does, but it never drops below 2rem on phones and never passes 3.5rem on huge monitors. One line replaces three media queries.

The companion trick for images belongs in almost every stylesheet:

img {
  max-width: 100%;
  height: auto;
}

Now any image shrinks to fit its container instead of overflowing on small screens.

Code exercise · javascript

clamp is simple enough to write yourself: the preferred value, pushed up to min if too small and down to max if too big. Run this JavaScript version to trace font-size: clamp(32px, 5vw, 56px) at three viewport widths.

Code exercise · javascript

Your turn: implement contentColumnWidth(viewportWidth) for the rule width: clamp(320px, 90%, 960px), where 90% means 90% of the viewport width. Reuse the clamp helper.

Quiz

font-size: clamp(2rem, 5vw, 3.5rem) on a 320px-wide viewport, where 5vw is 16px (1rem). What is the resulting size?

Problem

In clamp(2rem, 5vw, 3.5rem), what is the middle value called — the one the browser uses whenever it fits between the guardrails?