CSS Units Explained: px, em, rem, %, vw and calc()
Almost every layout property takes a length: width, padding, margin, font-size, gap. A length is a number immediately followed by a unit, with no space: 16px, 1.5rem, 50%. The only length you may write without a unit is 0.
Absolute: px
px is the CSS pixel. It is not a physical screen dot: on a high-density phone one CSS pixel may cover several device pixels, so 16px text looks about the same size on every screen. Pixels are predictable, which makes them a good fit for borders and small fixed details.
Relative to text: em and rem
remis relative to the font size of the root<html>element. Browsers default to16px, so1.5remis usually24px. If a reader raises their default font size, everything sized inremgrows with it. That makesremthe usual choice for font sizes and spacing.emis relative to the font size of the element itself (or, forfont-size, of its parent). It compounds: a1.2emlist inside another1.2emlist ends up 1.44 times larger. That is useful for padding that should scale with a button's own text, and surprising almost everywhere else.
Relative to space: % and viewport units
A percentage is relative to something that depends on the property. For width it is the width of the parent's content box: width: 50% takes half of it. Viewport units are relative to the browser window: 1vw is 1% of the viewport width and 1vh is 1% of its height. 100vh is a common way to make a full-screen hero section; on mobile, 100dvh (dynamic viewport height) accounts for browser toolbars appearing and disappearing.
Mixing units with calc()
calc() does arithmetic with mixed units, which plain CSS cannot otherwise do: width: calc(100% - 2rem) means "the full width minus two root-ems". Put spaces around + and - inside calc(); without them the expression is invalid.
The example sets sizes with four different units inside a 400-pixel-wide box and prints the pixel values the browser computed for each.
Expected page text
50% = 200px 10rem = 160px 10em at 20px = 200px calc(100% - 2rem) = 368px
The em box is the interesting one: its font size is 20px, so 10em of width resolves to 200px, not 160px.
Choosing a unit
- Font sizes:
rem, so user preferences are respected. - Spacing (padding, margin, gap):
rem, oremwhen it should track the element's own text. - Widths of columns:
%,frin Grid, or flexible Flexbox sizes. - Borders and hairlines:
px.
Summary
- A length is a number plus a unit with no space; only
0can drop the unit. remfollows the root font size,emthe element's font size,%usually the parent.calc()combines units; keep spaces around+and-.
Quiz: Units and sizes