June 28, 2025
O. Wolfson
When styling a webpage, understanding how CSS units work is key to building responsive, accessible, and scalable interfaces. Below, we break down the most common units—px, em, rem, %, vw, and vh—with visual examples.
px – Pixels (Fixed Size)Example:
html<div style={{ width: "300px", height: "50px", background: "lightblue" }}>
Fixed size box (100px x 50px)
</div>
Fixed size box (100px x 50px)
em – Relative to Element’s Font SizeExample:
html<div style="font-size: 20px;">
<div style="padding: 1em; background: lightgreen;">1em padding = 20px</div>
</div>
rem – Relative to Root Font Size<html>) element, usually 16px.em.Example:
html<div style="font-size: 24px;">
<div style="padding: 1rem; background: peachpuff;">
1rem padding = 16px (not 24px)
</div>
</div>
Note: This demo simulates em/rem math locally, but does not use real CSS rem units (which always depend on the root html font-size).
% – Percentage (Relative to Parent)Example:
html<div style="width: 300px; height: 100px; background: lightgray;">
<div style="width: 50%; height: 100%; background: lightcoral;">
50% width, 100% height
</div>
</div>
50% width, 100% height
vw / vh – Viewport Width / HeightDefinition:
1vw = 1% of viewport width1vh = 1% of viewport heightUse case: Fullscreen sections, dynamic typography, layout containers.
Caution: Can break layout on small devices if not handled carefully.
Example:
html<div style="width: 50vw; height: 30vh; background: skyblue;">
50vw x 30vh box
</div>
50vw x 30vh box
| Unit | Relative To | Common Use Cases | Scales With Font Size? |
|---|---|---|---|
| px | Absolute | Borders, icon size | ❌ |
| em | Parent font size | Padding, line height | ✅ |
| rem | Root font size | Consistent sizing across app | ✅ |
| % | Parent element | Widths, heights | ❌ |
| vw | Viewport width | Full-screen layouts, text | ❌ |
| vh | Viewport height | Hero sections, splash screens | ❌ |
You can test all these examples interactively here: 👉 CodePen Example – CSS Units Demo (or paste the HTML snippets above into your own playground)