| Unit | Relative to | Common use |
|---|---|---|
px |
nothing (absolute) | borders, precise 1px details |
% |
the parent element | widths, fluid layouts |
em |
the element's own font size | padding/margins that scale with text |
rem |
the root (<html>) font size |
font sizes — predictable, doesn't compound |
vw / vh |
1% of viewport width/height | full-bleed hero sections |
CSS
html { font-size: 16px; }
.title {
font-size: 2rem; /* 32px, always — relative to the root, not nesting */
}
.card {
padding: 1.5em; /* 1.5x THIS element's own font-size */
}
.hero {
height: 60vh; /* 60% of the viewport height */
}em compounds when nested (an em inside an element with a larger
em-based font-size gets bigger again), which surprises people — rem
avoids that by always referring back to the root, so it's the safer
default for font sizes. % for width is the workhorse of fluid,
responsive layouts.