CSS Units ยท Astro Tech Blog

Units

CSS has both absolute and relative units for sizing.

Demo: Absolute vs Relative Units
HTML
<div class="px">16px</div>
<div class="rem">1rem</div>
<div class="em">1em</div>
<div class="percent">50% width</div>
<div class="vw">10vw wide</div>
CSS
div { background: #6366f1; color: white; padding: 8px 16px; margin: 4px 0; border-radius: 6px; }
.px { width: 200px; }
.rem { width: 10rem; }
.em { width: 10em; font-size: 1rem; }
.percent { width: 50%; }
.vw { width: 30vw; }
Live Output Window

Absolute Units

UnitNameEquivalent
pxPixels1px = 1/96th of an inch
ptPoints1pt = 1/72nd of an inch
cmCentimetersโ€”
inInches1in = 96px

Relative Units

UnitRelative To
%Parent element
emParent font size
remRoot (html) font size
vwViewport width (1vw = 1%)
vhViewport height (1vh = 1%)
chWidth of โ€œ0โ€ character
exHeight of โ€œxโ€ character

Recommendation: Use rem for fonts, % for layout widths, and px for borders and small spacings.

Demo: Responsive Units
HTML
<div class="responsive">Resize the browser to see me change</div>
CSS
.responsive {
background: #059669;
color: white;
padding: 1rem;
border-radius: 6px;
width: 80vw;
max-width: 600px;
font-size: clamp(1rem, 3vw, 1.5rem);
}
Live Output Window