CSS Visual Styling: How to Use CSS Units

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


CSS units are used everywhere: lengths, paddings, margins, font sizes, and more.

Absolute Units

Pixels (px)

The most common unit. One CSS pixel doesn’t always equal one physical pixel (varies by device DPI).

div {
  width: 300px;
  padding: 20px;
}

Useful for print stylesheets:

  • cm - centimeters
  • mm - millimeters
  • in - inches (1in = 96px)
  • pt - points (1pt = 1/72 inch)
  • pc - picas (1pc = 12pt)

Relative Units

Percentages (%)

Relative to the parent element:

.parent {
  width: 800px;
}

.child {
  width: 50%;  /* 400px */
}

em

Relative to the element’s font size:

p {
  font-size: 16px;
  padding: 1.5em;  /* 24px */
}

Compounds when nested, which can be tricky.

rem

Relative to the root (html) font size:

html {
  font-size: 16px;
}

div {
  padding: 1.5rem;  /* Always 24px */
}

More predictable than em.

ch

Width of the “0” character:

input {
  width: 20ch;  /* Width of 20 zeros */
}

Useful for controlling line length.

Viewport Units

vw (Viewport Width)

1vw = 1% of viewport width:

.hero {
  width: 100vw;
  font-size: 5vw;
}

vh (Viewport Height)

1vh = 1% of viewport height:

.hero {
  height: 100vh;
}

vmin and vmax

Based on the smaller or larger viewport dimension:

.square {
  width: 50vmin;
  height: 50vmin;  /* Always square, fits viewport */
}

dvh, svh, lvh (Dynamic/Small/Large)

Modern units that handle mobile browser chrome:

.hero {
  height: 100dvh;  /* Adjusts as mobile chrome shows/hides */
}

Fraction Units (fr)

Used in CSS Grid to divide available space:

.grid {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
}

Which Unit to Use?

Use CaseRecommended Unit
Font sizesrem
Padding/marginrem or em
Fixed widthspx
Responsive widths%, vw
Full-height sectionsvh, dvh
Grid columnsfr

Best Practice

Set a base font size and use rem:

html {
  font-size: 16px;
}

h1 {
  font-size: 2rem;  /* 32px */
}

p {
  font-size: 1rem;  /* 16px */
  margin-bottom: 1.5rem;  /* 24px */
}

Lessons in this unit:

0: Introduction
1: How to Work with CSS Fonts
2: How to Style Text with CSS Typography
3: How to Use CSS Colors
4: How to Use CSS Backgrounds
5: How to Use CSS Filters
6: ▶︎ How to Use CSS Units
7: How to Use the CSS calc() Function
8: How to use Google Fonts
9: RGB color codes