CSS ยท Chapter 28 of 44

CSS Units

CSS supports absolute units like px, and relative units like %, em, rem, vw, and vh, each useful in different situations.

rem is relative to the root font size, em is relative to the parent element's font size, and vw/vh are relative to the viewport width/height.

Syntax
font-size: 1.5rem;
width: 50vw;

Absolute vs relative units

px is a fixed, absolute unit. Relative units like %, em, rem, vw, and vh scale based on context, making them better for responsive design.

rem vs em, and viewport units

rem always relates to the root (html) font size, avoiding compounding issues that em can have when nested. vw/vh relate to 1% of viewport width/height.

Example 1 (css)
html {
  font-size: 16px;
}
h1 {
  font-size: 2rem;
}
Output
The h1 renders at 32px (2 x 16px root font size)

rem multiplies against the root font-size, here 16px, giving 32px.

Key points

  • px is a fixed, absolute unit.
  • % is relative to the parent element.
  • rem is relative to the root font size; em is relative to the parent's font size.
  • vw and vh are relative to viewport width and height.
๐Ÿ’ก Note: Using rem for font sizes makes it easy to scale an entire site by changing one root value.

๐Ÿ“ Quick Quiz

1. What is rem relative to?

2. What is em relative to?

3. 1vw equals: