CSS Units Explained

Complete guide to all CSS measurement units with examples

📏
Absolute Units
px, pt, cm, in
Fixed-size units that appear as exactly the same size regardless of screen or device.
px (pixels) - width: 200px;
pt (points) - font-size: 12pt;
cm (centimeters) - width: 5cm;
in (inches) - padding: 0.5in;
mm (millimeters) - margin: 10mm;
📐
Relative Units
%, em, rem
Units relative to another length property. Essential for responsive design.
% (percentage) - width: 50%;
em (element) - font-size: 1.5em;
rem (root em) - padding: 2rem;
ch (character) - width: 20ch;
ex (x-height) - height: 2ex;
📱
Viewport Units
vw, vh, vmin, vmax
Relative to the size of the browser viewport. Perfect for full-screen layouts.
vw (viewport width) - width: 50vw;
vh (viewport height) - height: 100vh;
vmin (viewport minimum) - font-size: 5vmin;
vmax (viewport maximum) - padding: 2vmax;
🎯
Flexible Units
fr, min-content, max-content
Used in CSS Grid and Flexbox for creating flexible, responsive layouts.
fr (fraction) - grid-template-columns: 1fr 2fr;
min-content - width: min-content;
max-content - width: max-content;
fit-content - width: fit-content(200px);
auto - margin: auto;

Live Unit Demonstrations

200px (Fixed)
50% (Relative to parent)
20vw (20% of viewport width)
10rem (10 × root font size)

Unit Comparison Table

Unit Type Relative To Use Case Example
px Absolute Device pixel Fixed sizes, borders border: 1px solid #000;
% Relative Parent element Layout widths, heights width: 80%;
em Relative Parent font-size Typography scaling font-size: 1.2em;
rem Relative Root element font-size Consistent typography padding: 1.5rem;
vw Viewport Viewport width Full-width elements width: 100vw;
vh Viewport Viewport height Full-height sections height: 100vh;
vmin Viewport Smaller viewport dimension Mobile-responsive text font-size: 4vmin;
vmax Viewport Larger viewport dimension Large screen optimization padding: 2vmax;
fr Flexible Available space in grid CSS Grid layouts grid-template-columns: 1fr 2fr;

Detailed Unit Explanations

Viewport Units (vh, vw, vmin, vmax)

vh (Viewport Height) - 1vh = 1% of viewport height
vw (Viewport Width) - 1vw = 1% of viewport width
vmin - 1% of viewport's smaller dimension
vmax - 1% of viewport's larger dimension

Example: An element with height: 50vh will always be 50% of the visible screen height, regardless of scrolling.

Pixel (px) vs Relative Units

px is device-dependent and may not be the same physical size across devices.
Relative units adapt to user preferences and device characteristics.

em vs rem

em is relative to the font-size of its direct or nearest parent
rem is always relative to the root (html) element's font-size

Example: If html font-size is 16px, then 1rem = 16px everywhere, but 1em could be different in each context.

When to Use Which Unit?

Pro Tip: Use a combination of units! Example: width: min(1000px, 90vw) creates a responsive container that's never wider than 1000px or 90% of the viewport.