CSS Units (px, %, em, rem)
CSS Units (px, %, em, rem)
Understand the difference between fixed-size values and values that depend on surrounding typography or layout.
What you’ll learn
- Distinguish px, %, em and rem.
- Predict how relative padding responds to font size.
- Choose units based on the correct reference.
Understand the concept
px is a CSS pixel, a reference length used for many interface dimensions. % is relative to a property-specific reference size, often a containing block. em scales using a relevant font size (commonly the element’s font size for lengths), and rem scales from the root element’s font size.
Relative units are powerful, but be mindful: nested font sizes in em can compound, whereas rem generally avoids that nesting effect.
What the browser evaluates
Different units answer different questions: fixed design scale (px), context size (%), local font context (em), or root font context (rem).
Compare pixels and percentages
A 50% child uses half the containing block’s width.
HTML
<div class="track"><div class="half">50%</div></div>CSS
.track { width: 100%; background: #e2e8f0; padding: 8px 0; }
.half { width: 50%; background: #bfdbfe; padding: 8px; box-sizing: border-box; }Rendered output
Observe: The inner bar’s width is linked to its container, not a fixed pixel count.
Compare em and rem padding
Em padding scales with the element’s own font size.
HTML
<div class="units"><span class="small">1em padding</span><span class="large">1em padding</span></div>CSS
.units span { display: inline-block; background: #ccfbf1; padding: 1em; margin: 4px; }
.small { font-size: 12px; }
.large { font-size: 22px; }Rendered output
Observe: The larger text also gets more padding because both use em units.
Explain the result
Different units answer different questions: fixed design scale (px), context size (%), local font context (em), or root font context (rem).
Compare the two examples: identify the selector, each changed property, and which visible part of the output proves that the CSS took effect.
Common mistakes to avoid
- Percentages do not use the same reference for every CSS property.
- Em values for nested font sizes can compound in ways that are difficult to track.
Try it yourself
Change the large label padding to 1rem. Compare it with the other label at different font sizes.
Before changing the code, predict what will change. Then verify by checking the rendered result.
Check your understanding
What you should remember
Match units to the relationship you want: container, root type scale, or local typography.
Revisit the rendered examples if the rule still feels abstract. Change one declaration at a time so you can connect cause and effect.
Reaching the recap and completing the quizzes are separate milestones.