๐ŸŽ“ A1Learner
๐Ÿ”

CSS Units

A CSS unit names how a length is measured. Some units are fixed, and others scale with the page, the text or the viewport.

Em multiplies the size in effect

The box sets a font size of 20 pixels. The paragraph inside uses 0.8em, so its size comes out at 16 pixels.

.box {
  font-size: 20px;
}
.box p {
  font-size: 0.8em;
}

Rem uses the root size

The root element is the html element at the top of the page. Its font size is 16 pixels here, so 2rem gives 32 pixels.

h1 {
  font-size: 2rem;
}

Calc mixes units

The width uses calc() to take the full width and subtract 40 pixels. The top padding uses calc() to add 1em and 4 pixels, which gives 20 pixels.

.box {
  width: calc(100% - 40px);
  padding-top: calc(1em + 4px);
}

Vw uses the viewport width

The vw unit measures the width of the viewport, the visible area of the page. At a viewport 1000 pixels wide, 50vw gives a width of 500 pixels.

#demo {
  width: 50vw;
}

Example

h1 {
  font-size: 2rem;
}
.box {
  font-size: 20px;
  width: calc(100% - 40px);
}
.box p {
  font-size: 0.8em;
}
#demo {
  font-size: 1rem;
}

Key points

  • px is an absolute unit that does not depend on other elements.
  • em scales with the font size in effect for the element.
  • rem scales with the font size of the root element.
  • em can compound as elements nest inside each other.
  • vw measures a share of the viewport width, and vh measures a share of its height.
  • calc() mixes units inside one value.

In this example, the heading uses 2rem and reaches 32 pixels from the root size. The box sets a font size of 20 pixels and a width from calc(). The paragraph inside the box uses 0.8em and reaches 16 pixels. The demo paragraph uses 1rem and also reaches 16 pixels, this time from the root.

Note

Zero needs no unit, so a zero length is written as plain 0.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

The root font size is 16 pixels. What size does font-size: 2rem give?