Skip to content
css questions

CSS · 6 of 10junior~1 min

What is the difference between em, rem, px, vh, vw units?

#core#units

CSS Units

px - absolute pixels

Fixed size - not affected by user font size preferences.

css
.border { border: 1px solid; } /* always 1 pixel */

em - relative to parent font-size

css
.parent { font-size: 16px; } .child { font-size: 1.5em; } /* 24px */ .nested { font-size: 1.5em; } /* 36px - compounds! */

Compounding makes em tricky for font sizes but useful for spacing that should scale with the component's text.

rem - relative to root font-size

css
html { font-size: 16px; } /* root */ .any-element { font-size: 1.5rem; } /* always 24px, no compounding */

rem is predictable - always relative to <html>, never compounds.

vh / vw - viewport units

css
.hero { height: 100vh; } /* full viewport height */ .sidebar { width: 25vw; } /* 25% of viewport width */

dvh / svh / lvh - dynamic viewport units (modern)

css
/* accounts for mobile browser chrome (address bar) */ .hero { height: 100dvh; } /* dynamic viewport height */

When to use which

UnitBest for
pxBorders, shadows, media queries
remFont sizes, consistent spacing
emPadding/margin that scales with component text
vh / vwFull-screen sections, viewport-relative sizing
%Fluid widths relative to parent

Use rem for font sizes and most spacing. Use px only for borders and very small fixed values. Avoid em for font sizes due to compounding.

updated

did you know it?

related questions