DevAcademy
LearnCSSUnits & Values
BeginnerCSS

Units & Values

Learn the difference between absolute and relative CSS units, and when to use px, %, em, rem, vw, and vh.

Reading Time

14 min

Lesson

Lesson 6 of 30

Absolute vs Relative Units

CSS units fall into two categories: absolute units, which always represent the same physical size, and relative units, which scale based on another value like the parent’s font size or the viewport.

Common Units

UnitTypeRelative To
pxAbsoluteA fixed pixel size
%RelativeThe parent element’s corresponding size
emRelativeThe current element’s font size
remRelativeThe root (<html>) element’s font size
vwRelative1% of the viewport width
vhRelative1% of the viewport height

em vs rem

<style>
  html { font-size: 16px; }
  .parent { font-size: 20px; }
  .em-box { font-size: 1.5em; }   /* 1.5 x 20px = 30px */
  .rem-box { font-size: 1.5rem; } /* 1.5 x 16px = 24px, ignores parent */
</style>

<div class="parent">
  <p class="em-box">Sized with em (relative to parent)</p>
  <p class="rem-box">Sized with rem (relative to root)</p>
</div>
Output

Viewport Units

vw and vh are based on the browser’s viewport size, making them useful for full-height sections or text that scales with screen size.

Viewport Units Example

<style>
  .hero {
    width: 100%;
    height: 40vh;
    background: linear-gradient(to right, #4facfe, #00f2fe);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 5vw;
  }
</style>

<div class="hero">Hero Section</div>
Output

Percentages

Percentage values are always relative to some property of the parent element — for example, width: 50% means half the parent’s width, while height: 50% requires the parent to have an explicit height.

Unitless Line Height

line-height is one of the few properties commonly given without a unit (e.g. line-height: 1.5). A unitless value scales with the element’s own font size, which is usually what you want.

Best Practice

Use rem for font sizes and spacing so everything scales consistently with the user’s root font size (important for accessibility), and reserve px for things that should never scale, like a 1px border.

Interview Questions

Quick Quiz

1. What is rem relative to?

2. What is em relative to?

3. What does 1vw represent?