CSS Basics›Extra· 35 min read
CSS Units: px, %, em, rem, vw/vh
Sizes need units. Knowing which unit to use is the difference between rigid and flexible designs.
What you will learn
- Tell absolute and relative units apart
- Use px, %, em, rem, vw and vh
- Pick the right unit for the job
Absolute vs relative
Absolute units are fixed (px). Relative units scale with something else (the font, the parent, the screen). Relative units make designs flexible.
| Unit | Relative to | Use for |
|---|---|---|
px | Nothing (fixed pixels) | Borders, small fixed sizes |
% | The parent element | Flexible widths |
em | The current font-size | Spacing that scales with text |
rem | The root font-size | Font sizes (most reliable) |
vw / vh | 1% of viewport width / height | Full-screen sections |
<style>
.box { background: #e0e7ff; padding: 1rem; margin-bottom: 10px; }
.a { width: 50%; } /* half the parent */
.b { width: 200px; } /* fixed */
.c { font-size: 1.5rem; } /* 1.5 x root font */
.hero { height: 30vh; background: #4338ca; color: #fff; }
</style>
<div class="box a">width: 50% of parent</div>
<div class="box b">width: 200px (fixed)</div>
<div class="box c">font-size: 1.5rem</div>
<div class="box hero">height: 30vh of the screen</div>Live preview
Each box uses a different unit, and that is why they behave differently:
.a { width: 50% }— half the width of its parent. Make the preview wider and this box grows with it..b { width: 200px }— always exactly 200 pixels, no matter the screen. It never flexes..c { font-size: 1.5rem }— 1.5 times the root font size. If the page base is 16px, this text is 24px..hero { height: 30vh }— 30% of the viewport height (the visible screen). Resize the window taller and the box gets taller.
Note: Fixed units (px) stay put; relative units (%, rem, vh) stretch and shrink with something else. That flexibility is what makes a design adapt to phones and laptops.
Tip: A common, reliable habit: use rem for font sizes, % or fr (Grid) for widths, px for small fixed things like borders, and vh/vw for full-screen hero sections.
Q. Which unit is relative to the ROOT font size and is recommended for font sizes?
Answer: rem is relative to the root (html) font size, making it predictable and great for consistent typography.
✍️ Practice
- Make one box
50%wide and another300pxwide and compare as you resize the browser. - Set a hero section to
50vhtall and watch it change with the window height.
🏠 Homework
- Rewrite a layout that used only
pxto use%andreminstead, and note how it now flexes.