Free beginner tutorial

CSS Units: Pixels, Relative Lengths and Viewport Units

CSS units describe lengths for text, spacing, borders and layout. Choose a unit based on what the value should respond to: a fixed detail, a parent element, text size or the viewport.

Use pixels for precise details

A CSS pixel (px) is a fixed CSS length, not necessarily one physical screen pixel. It works well for small details such as a thin border. For text and larger spacing, relative units often adapt better to user settings and different layouts.

.card {
  border: 1px solid #dce3eb;
  border-radius: 8px;
}

Use percentages when size depends on a container

A percentage is resolved against a relevant containing size. It is useful when an element should take up part of its available space, such as a flexible column or image.

.sidebar {
  width: 30%;
}

img {
  max-width: 100%;
  height: auto;
}

Compare em and rem

em is relative to a font size. In a font-size declaration it is based on the parent’s font size; for many other properties it is based on the element’s own computed font size. Nested em-based text can grow or shrink as values compound.

rem is based on the root element’s font size, so it creates a more consistent scale across a page. It is commonly used for text, padding and gaps:

.card {
  padding: 1.25rem;
  font-size: 1rem;
}

.card h2 {
  font-size: 1.5rem;
}

Use viewport units with care

vw is one percent of the viewport width and vh is one percent of its height. These units can help size broad visual areas, but a heading sized only with viewport width may become too small on a phone or too large on a wide monitor.

Combine a preferred size with sensible limits using clamp():

.hero-title {
  font-size: clamp(2rem, 5vw, 4rem);
}

Build a layout that can shrink

For a centered page, combine a fluid available width with a maximum width. The side spacing remains on small screens, while the content stops growing on wide screens:

.page-shell {
  width: min(100% - 2rem, 72rem);
  margin-inline: auto;
}

Which CSS unit should I choose?

  • Use px for small, precise details such as borders.
  • Use % when an element’s size should relate to its container.
  • Use rem for a consistent site-wide text and spacing scale.
  • Use em when a value should follow a component’s own text size.
  • Use vw or vh for viewport-related sizing, with limits when needed.

There is no single best unit for every property. Start with the relationship you want, then check the layout at narrow and wide viewport sizes.

For readable text, see the CSS typography lesson. For flexible page layouts, continue with responsive design.