A Fun CSS Fact: Meet the Magic of clamp()
One declaration instead of three breakpoints for type sizes, plus the viewport-unit catch that bites in narrow sidebars.
First post, so I'll start with something small that I use constantly: clamp(). I picked it up while writing the same three media queries for every heading on a marketing site, adjusting font sizes at 480px, 768px, and 1200px, then doing it again on the next page.
What is clamp()?
clamp() takes a minimum, a preferred value, and a maximum. If the preferred value falls outside the range, the browser uses the nearest bound.
font-size: clamp(1rem, 2.5vw, 2rem);Paste it into dev tools and drag the window around to watch.
The Three Values
1remis the floor, so text stays legible on a phone.2.5vwis the preferred value. This is the part that scales with the viewport.2remis the ceiling, past which text stops growing and the layout doesn't turn into a poster.
The size tracks the window in the middle of the range and holds steady at both ends. No breakpoints involved.
Where It Helps
- Responsive font sizes: one declaration replaces a stack of media queries.
- Spacings and gaps: section padding that doesn't look cramped on mobile or cavernous on desktop.
- Width and height controls: a box that can grow and shrink but won't collapse or fill the screen.
Real-World Example
A heading that's readable in a narrow column and still reasonable on a wide monitor:
h1 {
font-size: clamp(1.5rem, 5vw, 3rem);
}- On small screens:
1.5rem - On big screens: up to
3rem - In-between: scales with the viewport width
The preferred value uses viewport units, so it ignores the container. Inside a narrow sidebar, 5vw on a 1400px window is 70px.
Other Lengths
clamp() works anywhere a length is accepted: shadows, margins, padding, border radii. Support is broad enough to skip the fallback.
If you've been writing breakpoints for type sizes, try a clamp.