7 The mathematics of color

 

This chapter covers

  • Converting color values between models
  • Creating harmonious color schemes and accessible colors
  • Switching between light mode and dark mode
  • Creating interesting visual effects with blend modes

Most developers start with CSS colors such #ff0000 or hsl(240 100% 50%) without understanding what's happening under the hood. But here's the thing: colors aren't just pretty decorations. They're mathematical constructs that follow precise rules. Understanding these rules will help you create better color schemes, fix accessibility issues, and implement advanced color effects that would otherwise seem like magic.

Think of this chapter as your bridge between "I know how to use CSS colors" and "I understand how colors actually work mathematically." By the end, you'll be manipulating colors like a pro, creating accessible designs with confidence, and impressing your colleagues with your newfound color wizardry.

7.1 Color models and color spaces

To really understand the math behind web colors, you need to learn first about color models and color spaces. The next few sections provide the details.

7.1.1 The RGB color model

RGB is the foundational color model for all digital displays. It’s based on additive color mixing where you're literally adding light to create colors. Mathematically, RGB represents colors as triplets (R, G, B) where each component ranges from 0 to 255:

7.1.2 The HSL color model

7.1.3 The LAB color space

7.1.4 The OKLCH color space

7.2 Converting between color models

7.2.1 Converting RGB to grayscale

7.2.2 Converting RGB to HSL

7.2.3 Converting HSL to RGB

7.3 Creating harmonious color schemes with math

7.3.1 Complementary colors

7.3.2 Analogous colors

7.3.3 Triadic colors

7.3.4 Split-complementary colors

7.4 Specifying accessible colors with math

7.4.1 The WCAG contrast requirements (AA vs. AAA)

7.4.2 The contrast ratio formula

7.4.3 Calculating relative luminance from color

7.4.4 Calculating contrast ratios with JavaScript

7.5 Light mode and dark mode mathematics

7.5.1 Why basic inversion doesn’t work

7.5.2 A better approach: inverting perceptual lightness

7.5.3 Hue and saturation adjustments for aesthetic consistency

7.5.4 Generating a paired light/dark palette

7.5.5 CSS implementation with media queries

7.6 The math behind blend modes and opacity

7.6.1 How blending works

7.6.2 Alpha compositing

7.6.3 Blending in CSS

7.6.4 The separable blend modes

7.6.5 The non-separable blend modes

7.7 Solutions to Exercises

7.8 Summary