agyanadda@gmail.com

CSS Units

Styling Elements 1 min read Updated Dec 1, 2026 Topic 10 of 39

CSS sizes need a unit (except 0).

Absolute unit

  • px — pixels. Fixed size.

Relative units

Unit Relative to
% the parent element
em the element's own font size
rem the root (html) font size, usually 16px
vw 1% of the viewport width
vh 1% of the viewport height

Which to use?

  • rem for font sizes and spacing (respects user settings)
  • % or vw for flexible widths
  • px for thin borders and small details

Example

Example — Comparing units HTML
<style>
  .px { font-size: 20px; }
  .rem { font-size: 1.5rem; }
  .half { width: 50%; background: #dbe8ff; padding: 8px; }
  .vw { width: 30vw; background: #ffe2d6; padding: 8px; margin-top: 8px; }
</style>

<p class="px">20px text</p>
<p class="rem">1.5rem text (24px)</p>
<div class="half">50% of parent width</div>
<div class="vw">30vw of the window</div>

Test Yourself With Exercises

Exercise 1 Multiple Choice

rem is relative to the font size of which element?

Exercise 2 Fill in the Blank

100___ equals the full height of the browser window.

Exercise 3 True / False

px is a relative unit.

Frequently Asked Questions

Prefer rem: it is always based on the root size, so it does not grow unexpectedly inside nested elements like em does.