CSS Units (px, em, rem, %, vw, vh)
CSS units define sizes for fonts, spacing, widths, and heights. Choosing the right unit is critical for responsive design. Absolute units (px) are fixed, while relative units (em, rem, %, vw, vh) adapt to context.
CSS Units Overview
- px — Pixels. Fixed size. 16px is 16px everywhere. Good for borders, shadows, precise values
- em — Relative to parent's font-size. 1.5em = 1.5× the parent font size. Can compound (nest problems)
- rem — Relative to root (html) font-size. 1rem = 16px by default. The best unit for fonts and spacing
- % — Relative to parent element. width: 50% = half the parent's width. Essential for responsive layouts
- vw — 1% of viewport width. 100vw = full screen width. Great for full-width sections
- vh — 1% of viewport height. 100vh = full screen height. Use for hero sections and full-page layouts
- ch — Width of the '0' character. max-width: 65ch = optimal reading width for paragraphs
Units Comparison
/* Fixed vs Relative units */
/* Pixels — fixed, doesn't scale */
h1 { font-size: 32px; }
/* rem — scales with user's browser settings */
h1 { font-size: 2rem; } /* 2 × 16px = 32px default */
/* em — relative to parent (can compound!) */
.parent { font-size: 20px; }
.child { font-size: 1.5em; } /* 30px (1.5 × 20px) */
/* Viewport units — responsive to screen size */
.hero {
height: 100vh; /* Full screen height */
width: 100vw; /* Full screen width */
font-size: 5vw; /* Scales with screen width */
}
/* Percentage — relative to parent */
.container { width: 80%; margin: 0 auto; }
/* Best practice: use rem for fonts, px for borders */
body { font-size: 1rem; }
.card { border: 1px solid #ddd; padding: 1.5rem; }Tip
Use rem for font sizes and spacing — it respects user accessibility settings. If a user increases their browser's default font size (common for visually impaired users), rem-based layouts adapt automatically. px-based layouts ignore this preference.
Use rem for fonts, % for widths, vw/vh for full-screen layouts
Common Mistake
Using em for nested elements causes compounding. If a parent is 20px and a child uses 1.5em (= 30px), a grandchild using 1.5em becomes 45px — not 30px! Use rem instead to avoid this unpredictable cascading effect.
Practice Task
Create a responsive hero section: (1) Set height to 100vh. (2) Set the heading font-size to 3rem. (3) Set paragraph max-width to 65ch for optimal readability. (4) Use padding in rem units. Resize your browser to see how rem and vh respond differently.
Quick Quiz
Key Takeaways
- CSS units define sizes for fonts, spacing, widths, and heights.
- px — Pixels. Fixed size. 16px is 16px everywhere. Good for borders, shadows, precise values
- em — Relative to parent's font-size. 1.5em = 1.5× the parent font size. Can compound (nest problems)
- rem — Relative to root (html) font-size. 1rem = 16px by default. The best unit for fonts and spacing