Sub topic 8
Fluid units: percentages, rem, vw, and clamp()
This chapter assumes you know basic HTML structure, CSS selectors and the cascade, the box model, and the units px, em, and rem. It also assumes you have read the earlier chapters on the viewport meta tag and on width-based media queries.
Media queries change a layout at fixed points. Fluid units fill the space between those points. A page built with fluid units resizes smoothly as the window changes, and the media queries only have to handle the places where the design needs a structural change.
Fixed versus fluid sizing
A fixed size, such as width: 600px, stays the same on every screen. On a 360px-wide phone, it forces horizontal scrolling. A fluid size is computed from something that changes: the parent's width, the root font size, or the viewport. The units in this chapter fall into three groups.
| Unit | Relative to | Typical use |
|---|---|---|
| `%` | The parent element (the property decides which dimension) | Widths, max-widths, padding in a fluid container |
| `rem` | The root (`html`) font size | Font sizes, spacing, breakpoints |
| `em` | The element's own font size (or its parent's, for `font-size`) | Spacing that should scale with local text |
| `vw`, `vh` | 1% of the viewport width or height | Large headings, full-screen sections |
| `ch` | Width of the "0" glyph in the current font | Line length for readable text |
Percentages
A percentage is resolved against a reference value that depends on the property. For width, the reference is the width of the containing block. The element therefore resizes whenever its container does.
.page {
width: 90%;
max-width: 60rem;
margin-inline: auto;
}
.main {
width: 66.6667%;
float: left;
}
.aside {
width: 33.3333%;
float: left;
}The .page rule shows a common pattern. The width is a percentage, so the page fills most of a small screen. The max-width caps it on large screens, so lines of text do not become too long to read.
Percentages do not always refer to the width. These cases catch many learners:
height: 50%only works if the parent has an explicit height. If the parent's height depends on its content, the percentage has nothing to resolve against and behaves likeauto.- Vertical
paddingandmarginpercentages are calculated from the containing block's width, not its height. This is howpadding-top: 56.25%creates a 16:9 box. font-size: 120%is relative to the parent's font size.- Percentages on
position: absoluteoffsets refer to the containing block's padding box.
rem for text and spacing
rem means "root em". It equals the font size of the html element. Browsers default to 16px, so 1rem is normally 16px. Users can change that default in their browser settings, and rem values follow the change. Pixel font sizes do not.
body {
font-size: 1rem;
line-height: 1.5;
}
h2 {
font-size: 1.75rem;
margin-block: 2rem 0.75rem;
}
.button {
padding: 0.75rem 1.25rem;
}Do not set html { font-size: 10px } to make the arithmetic easier. That overrides the user's preference. If you want 1rem to be easier to calculate, use html { font-size: 62.5% }. This keeps the user's setting as a baseline, but you then have to restore body text sizes explicitly, so many teams avoid it.
rem versus em
Both scale with text size, but they differ in what they follow. rem always follows the root, so 1.5rem means the same thing everywhere on the page. em follows the nearest font size, and that value compounds in nested elements. If a list inside a list has font-size: 0.9em, the inner list is 0.81 times the base size. Use rem for most sizing. Use em when a component's spacing should scale with its own text, such as button padding.
Media queries also resolve em and rem units against the browser's initial font size, not against any font-size set in your CSS. This is why min-width: 40em in the earlier cards example behaves consistently, and why it tracks the user's default text size.
Viewport units
1vw is 1% of the viewport width. 100vw is the full viewport width, and 50vh is half the viewport height. These values change with the window, so text or boxes sized with them are fluid without any media query.
.hero {
min-height: 60vh;
}
.hero h1 {
font-size: 6vw;
}Viewport units have three well-known problems.
- Scrollbars.
100vwincludes the width of a vertical scrollbar. On systems with classic scrollbars,width: 100vwmakes the page about 15px wider than the visible area and creates a horizontal scrollbar. Usewidth: 100%for full-width blocks. - Mobile browser toolbars. On phones, the address bar slides in and out, so the visible height changes while the user scrolls.
100vhis measured with the toolbar retracted, so a "full-screen" section can extend below the visible area. Modern browsers offersvh(small viewport height),lvh(large), anddvh(dynamic, updates as the toolbar moves).min-height: 100svhis a safe choice for a full-screen section. - Accessibility. Text sized only in
vwdoes not respond to the user's font-size setting or browser zoom in the expected way. At a 320px width,6vwis only about 19px, and at 2000px it is 120px. Purevwtext has no lower or upper limit.
The third problem leads to clamp().
clamp() for bounded fluid values
clamp(min, preferred, max) returns the preferred value, unless it falls below the minimum or above the maximum. It is a one-line replacement for several media queries that step a font size up.
h1 {
font-size: clamp(1.5rem, 4vw + 1rem, 3rem);
}For this heading:
- The preferred value,
4vw + 1rem, is a calculation that mixes a viewport unit and arem. It grows as the viewport widens. - At a 320px viewport, it is about 12.8px + 16px = 28.8px, which is above the 24px (1.5rem) minimum, so the preferred value is used.
- At 1200px, it is 48px + 16px = 64px, which is above the 48px (3rem) maximum, so the heading stops growing at 48px.
Adding the rem term to the vw term is deliberate. Because part of the value is a rem, the result still responds when users zoom or raise their default font size. That fixes most of the accessibility problem of pure vw text.
clamp() works for any length, not only fonts:
.section {
padding-block: clamp(1.5rem, 5vw, 4rem);
padding-inline: clamp(1rem, 4vw, 3rem);
}
.container {
width: min(90%, 70rem);
margin-inline: auto;
}The second rule uses min(), a related function that picks the smaller of its arguments. min(90%, 70rem) does the same job as width: 90%; max-width: 70rem. A matching max() function picks the larger value. All three functions allow arithmetic inside, so you can write clamp(1rem, 2vw + 0.5rem, 2rem) without wrapping it in calc().
Derive the preferred value
To make a value grow linearly from a size a at viewport width w1 to a size b at w2, you need a slope and an offset:
- slope = (b − a) / (w2 − w1)
- offset = a − slope × w1
For a font size that goes from 16px at 400px to 32px at 1200px, the slope is 16 / 800 = 0.02, which is 2vw. The offset is 16 − 0.02 × 400 = 8px, or 0.5rem. The result is:
p.lead {
font-size: clamp(1rem, 2vw + 0.5rem, 2rem);
}Combining fluid units with media queries
Fluid units do not replace media queries. They handle gradual change in size, spacing, and width. Media queries handle changes of structure, such as going from one column to three or turning a menu into a hamburger button. A typical stylesheet uses both.
The example below uses both in a single component.
.cards {
display: grid;
gap: clamp(0.75rem, 2vw, 1.5rem);
grid-template-columns: 1fr;
padding: clamp(1rem, 4vw, 3rem);
}
@media (min-width: 40em) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}The gap and padding grow smoothly. The column count changes only once, at the breakpoint.
Common errors
- Using
vwalone for font sizes, with no minimum or maximum. - Writing
clamp(3rem, 4vw, 1.5rem), with the minimum and maximum swapped. When min is larger than max, the minimum wins, so the value never changes. - Writing
clamp(1rem, 2vw + 1rem, 2rem)asclamp(1rem, 2vw+1rem, 2rem). Inside math functions,+and-need spaces on both sides. - Using
height: 100%without a defined parent height. - Setting
html { font-size: 16px }, which blocks the user's default size. - Mixing units in
calc()and forgetting thatcalc(100% - 2rem)is valid butcalc(100% - 2)is not.
Exercise
A heading should be 1.25rem on narrow screens, grow with the viewport, and stop at 2.5rem. Write a font-size declaration using clamp() and explain why the preferred value includes a rem term as well as a vw term.
Show answer
One answer is font-size: clamp(1.25rem, 3vw + 0.5rem, 2.5rem);. The vw term makes the size grow with the viewport. The rem term keeps part of the value tied to the root font size, so the heading still responds to the user's browser font-size setting and to zoom. The first and last arguments keep the size from becoming too small or too large.
Exercise
A full-width banner uses width: 100vw and a horizontal scrollbar appears on desktop. What is the cause, and what is a fix?
Show answer
100vw includes the width of the vertical scrollbar, so the banner is wider than the visible area. Use width: 100% (or omit the width on a block element), which is based on the containing block and excludes the scrollbar.