CSS BasicsExtra· 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.

UnitRelative toUse for
pxNothing (fixed pixels)Borders, small fixed sizes
%The parent elementFlexible widths
emThe current font-sizeSpacing that scales with text
remThe root font-sizeFont sizes (most reliable)
vw / vh1% of viewport width / heightFull-screen sections
Different units in action
<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

  1. Make one box 50% wide and another 300px wide and compare as you resize the browser.
  2. Set a hero section to 50vh tall and watch it change with the window height.

🏠 Homework

  1. Rewrite a layout that used only px to use % and rem instead, and note how it now flexes.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →