CSS Units and Values: rem, clamp, and Fluid Sizing
A length in CSS is never just a number â it is a number attached to a reference point, and choosing the reference point is the whole design decision. Pixels reference the screen's device pixels; rem references the root font size; em references the current element's font size; percentages reference the containing block; viewport units reference the browser window. When a layout breaks only on a phone, or a heading that looked right in a mockup explodes on a large monitor, the culprit is almost always the unit. This lesson maps the unit families to their reference points, walks through the modern math functions (clamp, min, max, calc) that replaced most media-query gymnastics, and shows how to build fluid type and spacing that hold up from 320px phones to ultrawide displays.
Pixels are precise, but they are also local knowledge
Pixels are absolute and predictable, which makes them tempting and occasionally wrong. A 16px heading does not scale when a user raises their browser's default font size, so settings-conscious accessibility testing flags fixed-pixel text that should have been in rem. Borders, shadows, and hairline dividers are different: a 1px border genuinely should be 1px, and converting it to rem adds noise without benefit. The working rule used across most mature design systems is: text and spacing in rem (or em inside component code), structural hairlines and fixed UI chrome in px. Percentages are the unit of layout â widths of flex and grid children, paddings relative to the parent's inline size â and mixing them with the absolute units inside calc() is normal, not a hack.
rem versus em: two different reference points
rem means root em: every rem multiplies the font size set on the html element, which browsers default to 16px. Because that root never changes as you nest, rem values stay stable anywhere in the stylesheet. em is context-sensitive: inside an element it refers to that element's own computed font size for fontSize declarations, and to the inherited font size for almost everything else. That double behavior is powerful inside components â a card with padding: 1em automatically grows when its text grows â and dangerous when font-size itself is in em, because sizes compound down the tree: a child at 1.5em inside a parent at 1.5em renders at 2.25 times the grandparent.
| Unit | References | Typical use | Compounding risk |
|---|---|---|---|
| px | Device-independent pixels | Borders, shadows, tight chrome | None; does not scale with user settings |
| rem | Root (html) font size | Type scale, spacing scale | None; stable at any nesting depth |
| em | Element's own or inherited font size | Component-internal padding, icon sizing | Yes, when fontSize itself uses em |
| % | Containing block | Layout widths, fluid padding | None |
| vw / vh | Viewport width / height | Full-bleed sections, hero heights | Mobile browser chrome changes vh |
| dvh / svh / lvh | Dynamic, small, large viewport | Mobile-safe full-height layouts | None; tracks the real visible area |
| ch / ex / cqi | Character width, x-height, container inline size | Readable line lengths, container-relative type | None |
For most projects, authoring the type scale in rem at the root and deriving everything else from a handful of custom properties gives you a global zoom control for free: change one html { font-size } and the whole interface scales proportionally.
Viewport units and the dvh fix
Viewport units feel ideal for full-screen heroes: height: 100vh is exactly the viewport. On mobile browsers, however, the visible area changes as the URL bar collapses during scroll, so 100vh often reserves more height than the user can see â content sits under the browser chrome or the page scrolls a few extra pixels. The dynamic viewport unit dvh tracks the current visible height: 100dvh shrinks and grows as the bar moves. The small and large variants (svh, lvh) let you freeze to either extreme, which is useful when you want a stable layout and will compensate manually. The progressive-enhancement pattern is to declare the fallback first and the dynamic value second:
.hero {
min-height: 100vh; /* fallback for old engines */
min-height: 100dvh; /* real visible viewport */
display: grid;
place-items: center;
padding: clamp(1.5rem, 4vw, 4rem);
}
.readable {
max-width: 68ch;
line-height: 1.6;
}
ch, the width of the zero glyph, is a quiet hero for prose: setting max-width in ch keeps line length comfortable across fonts and sizes without hard-coding pixel widths that break when text scales.
clamp() as a one-line responsive system
clamp(min, preferred, max) returns the preferred value clamped between the bounds, and the preferred value is usually a viewport-relative calculation. That collapses an entire media-query ladder into one declaration: font-size: clamp(1.25rem, 1rem + 1.2vw, 2rem) starts at 20px on the smallest screens, grows smoothly with the viewport, and stops at 32px on large screens. Because the middle term mixes rem and vw through addition, it also respects the user's root font size â a purely vw-based clamp would not. The same function works for spacing and containers, not just type:
:root {
--step-0: clamp(1rem, 0.95rem + 0.25vw, 1.125rem);
--step-1: clamp(1.25rem, 1.15rem + 0.5vw, 1.5rem);
--step-2: clamp(1.5rem, 1.3rem + 1vw, 2rem);
--step-3: clamp(2rem, 1.6rem + 2vw, 3rem);
--gap: clamp(1rem, 0.8rem + 1vw, 2rem);
}
h1 { font-size: var(--step-3); }
h2 { font-size: var(--step-2); }
p { font-size: var(--step-0); }
.section {
padding: var(--gap);
display: grid;
gap: var(--gap);
}
Two traps to avoid: never put the same unit in all three arguments without checking the math (clamp(16px, 4vw, 24px) is fine, but clamp(4vw, 16px, 2vw) makes no sense because the preferred value sits outside the bounds and will pin to one end forever); and remember that clamped values are static per viewport â they do not re-render continuously as you drag, which is usually invisible but matters in split-screen windows.
min(), max(), and calc() working together
min() and max() pick the smaller or larger of their arguments, which makes them ideal for guardrails: width: min(100%, 72rem) gives a centered column that never overflows a narrow screen; height: max(24rem, 80vh) keeps a panel tall enough to be useful on short laptops without wasting space on tall ones. calc() handles mixed-unit arithmetic that used to require JavaScript or magic numbers â width: calc(100% - 200px) for a sidebar split, padding-inline: calc(var(--gap) / 2). Nesting is allowed, so calc(max(200px, 50%) + 1rem) is valid, but readability decays fast; when an expression needs more than one nesting level, introduce a custom property and compose from it instead.
aspect-ratio completes the set for media: aspect-ratio: 16 / 9 with width: 100% gives every video thumbnail the same shape without hardcoded heights, and object-fit: cover on the image keeps the crop clean.
Container query units for component-scale sizing
Viewport units answer to the window, not to the component, so a card used in both a wide sidebar and a narrow drawer looks identical either way. Container query units (cqi, cqb, cqw, cqh) reference the query container instead, and they work without a @container rule: set container-type: inline-size on the wrapper, then size the child with font-size: max(1rem, 2.5cqi) and the text grows with the card, not the screen. Combined with clamp, this produces components that adapt to wherever they are embedded â the whole point of the container queries lesson. Support is now broad enough for production, but keep a plain rem fallback declaration before the cqi line for older engines.
Common Mistakes
Full-height sections jump or show a gap under the mobile URL bar
Fix: Declare min-height: 100vh as a fallback, then override with 100dvh so the layout tracks the real visible viewport
Type does not scale when the user changes browser font size
Fix: Author font sizes in rem (or em) instead of px so user settings propagate through the root font size
Nested font sizes compound into giant text
Fix: Use rem inside components, or reserve em for non-fontSize properties such as padding and icon sizing where compounding is intended
clamp() values pin to one bound and never move
Fix: Check that the preferred value actually falls between min and max across your viewport range, and mix rem with vw so user settings still apply
Best Practices
- Define a small type and spacing scale with clamp() and custom properties, then reference the variables everywhere
- Use min(100%, max-width) for content columns so they never overflow narrow screens
- Prefer dvh over vh for anything that must match the visible mobile viewport
- Size prose with ch units (max-width: 68ch) for font-independent readability
- Declare fallback values on a separate line before the modern unit so older browsers degrade gracefully
Interview Questions
Q1: What is the practical difference between rem and em?
rem always resolves against the root html font size, so its computed value is the same anywhere in the document. em resolves against the element's own font size for fontSize declarations and against the inherited font size for other properties, which makes it powerful for self-scaling components but risky because sizes compound as you nest.
Q2: Why does 100vh misbehave on mobile browsers, and what fixes it?
Mobile browsers dynamically show and hide their URL bar, so the small viewport and the large viewport differ while 100vh resolves to the larger one. That leaves content hidden behind the chrome or causes extra scrolling. The dvh unit tracks the current visible height and fixes the mismatch; svh and lvh let you pin either extreme.
Q3: Write a fluid heading that scales from 24px to 40px.
fontSize: clamp(1.5rem, 1rem + 2vw, 2.5rem). The preferred term mixes rem with vw so the ramp is both viewport-responsive and sensitive to the user's root font size, while the bounds guarantee a floor of 24px and a ceiling of 40px.
Key Takeaways
- Every unit has a reference point â px is the screen, rem the root font size, em the element, % the containing block, vw/vh the viewport, cqi the query container
- Use rem for text and spacing so user fontSize settings work; keep hairlines and chrome in px
- vh is unreliable on mobile; dvh tracks the visible viewport and svh/lvh pin its extremes
- clamp(min, preferred, max) replaces media-query ladders for type and spacing; mix rem with vw in the preferred term
- min(), max(), and calc() supply guardrails and mixed-unit math; aspect-ratio locks media shape without hardcoded heights