Values and visual language

Colors

Express colors with named values, hexadecimal, rgb, and hsl syntax while checking contrast between text and its background.

CSS gives you several ways to write the same color. Here are the four you’ll see most, all describing the same purple:

.examples {
  color: rebeccapurple;
  border-color: #663399;
  background: rgb(102 51 153 / 15%);
  outline-color: hsl(270 50% 40%);
}
  • A named color like rebeccapurple. There are about 150 of them. Handy for quick tests, rarely precise enough for a design.
  • Hex: #663399. Two hex digits each for red, green, and blue. Compact, and what design tools copy to your clipboard.
  • rgb(): the same three channels as numbers from 0 to 255.
  • hsl(): hue as an angle on the color wheel, then saturation and lightness as percentages.

The modern syntax separates channels with spaces, not commas. For transparency, add a slash and an alpha value, like the / 15% above. The old rgba() comma form still works, but I’d write the new one.

Pick the format that makes edits easy

I use hex for values copied from a design. I switch to hsl() when I need a family of related colors. Want a darker hover state? Keep hue and saturation, lower the lightness. With hex you’d be guessing digits.

Alpha is not “lighter”

rgb(102 51 153 / 15%) is not a light purple. It’s purple at 15% opacity, and what you see depends on what’s behind it. Over white it looks pale. Over a dark photo it nearly disappears. Check alpha colors on the real background, not on a swatch.

currentColor

currentColor is a keyword that means “this element’s text color”. It keeps decorations in sync with the text:

.notice {
  color: #2457d6;
  border: 2px solid currentColor;
}

Change color and the border follows. Inline SVG icons use the same trick to pick up the surrounding text color.

Contrast

Text has to be readable against its background. The common target is a contrast ratio of at least 4.5:1 for body text. Light gray on white fails every time, even when it looks elegant on your monitor.

DevTools helps here. Click the swatch next to a color declaration and the picker shows the contrast ratio against the background, with a pass or fail mark. I check it on every text color I set.

Also, never let color be the only signal. A red border alone doesn’t tell a colorblind user the field has an error. Add text, an icon, or another visible cue.

Some users turn on a high-contrast mode in their operating system, and the browser replaces your colors with theirs. Let it. DevTools can emulate forced-colors so you can check the page still makes sense.

Try this on the course page. Give the nav links a normal, hover, and focus color, and run the contrast check on each state. Then imagine the page in grayscale. If a link no longer communicates its state, add something besides color.

Lesson completed