CSS colours and units: px, rem, em, % and vw

Beginner  Nov 3, 2026

Pick colour formats and sizes that scale well on every screen.

CSS colours and units: px, rem, em, % and vw
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

Colours

color: #1e40af;                 /* hex */
color: rgb(30 64 175);
color: hsl(224 71% 40%);        /* easy to adjust: hue, saturation, lightness */
background: rgb(0 0 0 / 0.5);   /* 50% transparent */

HSL is friendly: keep the hue, change lightness for lighter and darker shades.

How the code in this section fits into the page.
How the code in this section fits into the page.

Units

  • px: fixed pixels. Good for borders and shadows.
  • rem: relative to the root font size (16px by default). Best for font sizes and spacing, because it respects the user's browser settings.
  • em: relative to the element's own font size.
  • %: relative to the parent.
  • vw / vh: 1% of the screen width / height.
html { font-size: 100%; }
h1   { font-size: 2.25rem; }       /* 36px by default */
.box { padding: 1.5rem; max-width: 60rem; }
.hero { min-height: 70vh; }
The main points of this section.
The main points of this section.

Contrast

Text must be readable. Aim for a contrast ratio of at least 4.5:1 for normal text (WCAG AA). Free contrast checkers show the ratio for any two colours.

Contrast
Contrast

Tip

Do not set html { font-size: 62.5% } tricks without a reason. Plain rem values work well.

More tutorials