CSS Units

By

Learn how CSS units work, from pixels and percentages to relative units like em, rem, ex, and ch, plus viewport units and real-world measurements.

~~~

One of the things you’ll use every day in CSS are units. They are used to set lengths, paddings, margins, align elements and so on.

Things like px, em, rem, or percentages.

They are everywhere. There are some relatively unknown ones, too.

Pixels

The most widely used measurement unit. A pixel does not actually correlate to a physical pixel on your screen, as that varies, a lot, by device (think high-DPI devices vs non-retina devices).

There is a convention that make this unit work consistently across devices.

Percentages

Another very useful measure, percentages let you specify values in percentages of that parent element’s corresponding property.

Example:

.parent {
  width: 400px;
}

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

Real-world measurement units

We have those measurement units which are translated from the outside world. Mostly useless on screen, they can be useful for print stylesheets. They are:

Relative units

To quickly convert between px, rem and em, try my free CSS units converter.

Viewport units

Classic vh can mis-handle mobile browser UI chrome. The address bar shows and hides, and 100vh often does not match what you see. That is why we also have these variants, which are Baseline Widely available:

For full-height sections on phones I prefer 100dvh (or calc(100dvh - …) when you need calc()). The same sv* / lv* / dv* prefixes exist for width and the min/max forms.

There are also container query units like cqw and cqh, which size relative to a containment context instead of the viewport.

Fraction units

fr are fraction units, and they are used in CSS Grid to divide space into fractions.

Tagged: CSS · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about css: