How HEX and RGB Color Codes Work in Web Development
Every digital display uses tiny subpixels of Red, Green, and Blue (RGB) light to render color. Understanding how hexadecimal math translates into display signals is essential for optimizing design systems and writing clean CSS.
1. Hexadecimal Color Math Explained
A standard 6-digit hex code represents a base-16 number where each digit ranges from 0 to 15 (0â9 followed by AâF). The 6 characters are split into three pairs:
- Digits 1â2 (Red): From
00 (0 intensity) to FF (255 max intensity).
- Digits 3â4 (Green): From
00 (0 intensity) to FF (255 max intensity).
- Digits 5â6 (Blue): From
00 (0 intensity) to FF (255 max intensity).
/* Formula: Converting #2563EB to RGB */
R = (2 Ã 16) + 5 = 37
G = (6 Ã 16) + 3 = 99
B = (14 Ã 16) + 11 = 235
/* CSS Equivalents */
background-color: #2563eb;
background-color: rgb(37, 99, 235);
background-color: hsl(221, 83%, 53%);
2. When to Use HEX vs. RGB vs. HSL
Different color formats excel in different frontend scenarios:
- HEX: Ideal for hardcoded brand constants and static design mockups due to its compact 7-character notation.
- RGB / RGBA: Useful when defining alpha transparency via CSS custom properties:
rgba(var(--brand-rgb), 0.15).
- HSL (Hue, Saturation, Lightness): Ideal for design tokens and accessible hover states. By holding Hue and Saturation constant while increasing Lightness by 10%, you create mathematically harmonious button hovers and focus borders without altering tone.
Frequently Asked Questions
How do I convert HEX to RGB in my head? +
Multiply the first hex character by 16 and add the second character value (where A=10, B=11, C=12, D=13, E=14, F=15). For example, 3A = (3Ã16) + 10 = 58. Repeat for the green and blue character pairs.
Why does HSL make design system development easier? +
HSL maps directly to human perception. Hue (0â360°) controls the rainbow color family, Saturation (0â100%) controls vibrancy, and Lightness (0â100%) controls illumination. This allows you to generate accessible 50-950 scales using single-variable CSS math.
What is WCAG AA and AAA color contrast? +
The Web Content Accessibility Guidelines (WCAG 2.1) require normal body text to achieve at least a 4.5:1 contrast ratio against its background (Level AA), or 7:1 for enhanced accessibility (Level AAA). For large headings (18pt+ or 14pt bold), 3:1 is required.