clamp() for Responsive Values
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
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.
| Argument | Role |
|---|---|
| Minimum | The smallest the value is ever allowed to be |
| Preferred | A flexible value (often using vw) that scales with viewport size |
| Maximum | The 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.