Beginner LevelCSS & Modern Layouts
What are the differences between CSS units: px, em, rem, %, vh, vw?
❓ Interview Prompt: Compare absolute and relative CSS length units and when to use each for responsive design.
CSS provides absolute and relative units for sizing:
Absolute Units:
•
`px`: Fixed pixel size. Does not scale with user font preferences. Use for borders, shadows, fine-grained control.
Relative Units:
•
`em`: Relative to the parent element's font-size. Compounds when nested (1.2em × 1.2em = 1.44em).
•
`rem`: Relative to the root (`<html>`) font-size (usually 16px). Consistent and non-compounding. Best for typography and spacing.
•
`%`: Relative to the parent's corresponding dimension (width, height, font-size depending on context).
•
`vh` / `vw`: 1% of the viewport height / width. Use for full-screen hero sections.
•
`dvh`: Dynamic viewport height — accounts for mobile browser chrome (address bar collapse). Preferred over
vh in 2026.Code Implementation Example
css
html { font-size: 16px; } /* 1rem = 16px */
body { font-size: 1rem; } /* 16px */
h1 { font-size: 2.5rem; } /* 40px, scales with root */
p { font-size: 1rem; } /* 16px */
.hero {
height: 100dvh; /* Full viewport, mobile-safe */
padding: 2rem; /* 32px, consistent spacing */
}
.sidebar { width: 25%; } /* 25% of parent width */
.border { border: 1px solid #3d2c2e; } /* px for fine lines */💡rem for typography, dvh for viewport sections, px for borders.
🎯 Interview Key Takeaway
Use rem for font sizes and spacing, dvh/dvw for viewport dimensions, and px only for borders and fine details.
#Units#Responsive#Typography#Beginner
Back to all CSS & Modern Layouts Questions→