What are relative, absolute, and fixed CSS units?
· Category: HTML & CSS
Short answer
Absolute units (px, pt, cm) are fixed in size, while relative units (em, rem, %, vw, vh) scale based on parent elements, root font size, or viewport dimensions.
How it works
- px: Fixed pixel size; useful for borders and precise design constraints.
- rem: Relative to the root (
<html>) font size. Ideal for typography because changing the root size scales the entire UI. - em: Relative to the parent element's font size. Useful for component-scaled spacing but can compound unpredictably.
- vw/vh: Percentage of viewport width or height. Great for full-bleed sections and responsive typography.
- %: Relative to the parent element's corresponding dimension.
Example
html {
font-size: 16px;
}
h1 {
font-size: 2rem; /* 32px */
margin-bottom: 1em;
}
.hero {
height: 100vh;
padding: 5vw;
}
Why it matters
Relative units make your designs accessible and responsive. Users who change their browser's base font size for readability will see your layout scale appropriately when you use rem and em for typography and spacing.