Colours, units and values

CSS · Essentials · 10 min

Picking the right unit is the difference between a layout that scales with user settings and one that breaks.

Colours can be written several ways:

  • Keywords: red, rebeccapurple, transparent, currentColor (the element's text colour).
  • Hex: #1e90ff, with alpha #1e90ff80.
  • rgb(30 144 255 / 50%) and hsl(210 100% 56%), in the modern space-separated syntax.
  • oklch(65% 0.2 250): lightness, chroma, hue. It's perceptually uniform, so equal lightness steps look equal, which makes palettes easy. All current browsers support it.

Lengths come in two families.

  • Absolute: px is the practical one (a reference pixel, not a device pixel).
  • Relative: rem is relative to the root font size (16px by default, and user-adjustable), em to the element's own font size (for font-size itself, the parent's), % to the parent's corresponding dimension, vw/vh to 1% of the viewport width/height, and ch to the width of a "0".

A good default: rem for font sizes and most spacing, so everything scales when a user raises their browser's font size; px for borders and hairlines; % or fr for layout widths. em compounds when nested, which is handy for padding that scales with a button's own text, but confusing for font sizes in nested lists.

On phones, 100vh can be taller than the visible area because of browser toolbars. Use 100dvh (dynamic viewport height) or 100svh (smallest) instead.

calc() mixes units: calc(100% - 2rem).

Example

:root { font-size: 100%; }          /* respects the user's setting (16px default) */

.card {
  color: #1f2937;
  background: oklch(97% 0.02 250);   /* very light blue */
  border: 1px solid rgb(0 0 0 / 10%);
  padding: 1.5rem;                   /* 24px at default size */
  max-width: 60ch;                   /* comfortable line length */
  width: calc(100% - 2rem);
}

.card button { font-size: 0.875rem; padding: 0.5em 1em; } /* em = scales with its text */
.hero { min-height: 100dvh; }        /* full visible height on mobile */
.icon { fill: currentColor; }        /* follows the text colour */

Remember

  • rem for type and spacing, px for borders
  • oklch gives perceptually even colours
  • Use dvh/svh instead of vh for full-height mobile layouts
  • calc() mixes units

Watch out for

  • Setting html { font-size: 62.5% } tricks or px-only fonts that ignore the user's preferred text size.

Check yourself

  1. With the default root font size, .box { font-size: 20px; padding: 2em; } has how much padding?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/color_value