CSS Color Formats: Hex, rgb() and hsl(), and Text Contrast
CSS gives you several ways to write the same color. #ff8800, rgb(255 136 0) and hsl(32 100% 50%) are one and the same orange. Each format suits a different job: hex is compact and what design tools export, rgb() maps directly to screen channels, and hsl() makes it easy to create lighter, darker or muted variations. This page explains each one, shows how to convert between them, and covers the part that matters most for users: whether text on your colors is readable.
The CSS here works in all current browsers. The conversion and contrast code is JavaScript for Node.js 22 or later or a current browser, and its output is real.
Hex colors
A hex color is # followed by red, green and blue values in hexadecimal, two digits each, from 00 (none) to ff (255, full). In #ff8800: red ff = 255, green 88 = 136, blue 00 = 0.
- Three-digit shorthand:
#f80doubles each digit, so it equals#ff8800. It only works when each pair is a repeated digit. - Alpha (transparency): add a fourth pair,
#ff880080, or a fourth digit in shorthand,#f808.80is 128 out of 255, about 50% opaque. - Hex is case-insensitive:
#FF8800and#ff8800are identical.
rgb()
rgb() writes the same three channels as decimal numbers from 0 to 255 (or percentages), with optional alpha after a slash:
rgb(255 136 0): modern syntax, spaces between values.rgb(255 136 0 / 50%)or/ 0.5: half transparent.rgb(255, 136, 0)andrgba(255, 136, 0, 0.5): the older comma syntax, still valid.rgba()is now just an alias ofrgb(). Do not mix styles within one value: commas and slash together is an error, and the browser ignores the whole declaration.
hsl()
hsl() describes a color the way people tend to think about it:
- Hue: an angle on the color wheel, 0 to 360. 0 is red, 120 green, 240 blue; 32 is orange.
- Saturation: 0% is gray, 100% is the most vivid version of the hue.
- Lightness: 0% is black, 100% is white, 50% is the pure color.
Its strength is variation. Keep the hue, change the lightness, and you have a hover state, a border or a pale background that belong to the same color family: hsl(32 100% 50%), hsl(32 100% 40%), hsl(32 100% 95%). Note that equal lightness values do not look equally light across hues: yellow at 50% looks much brighter than blue at 50%. That is why contrast has to be measured, not guessed from the numbers.
Converting between formats
Hex to rgb() is just base 16 to base 10 for each pair. RGB to HSL takes a little arithmetic: lightness is the average of the largest and smallest channel, saturation comes from their difference, and hue from which channel is largest. In JavaScript:
// Hex (#rgb, #rgba, #rrggbb or #rrggbbaa) to { r, g, b, a }
function hexToRgb(hex) {
let h = hex.replace(/^#/, "");
if (!/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(h)) {
throw new Error(`Not a hex color: ${hex}`);
}
if (h.length <= 4) h = [...h].map((c) => c + c).join(""); // f80 -> ff8800
const n = (i) => parseInt(h.slice(i, i + 2), 16);
return { r: n(0), g: n(2), b: n(4), a: h.length === 8 ? n(6) / 255 : 1 };
}
// RGB (0-255) to HSL (degrees, percent, percent)
function rgbToHsl({ r, g, b }) {
const [R, G, B] = [r / 255, g / 255, b / 255];
const max = Math.max(R, G, B);
const min = Math.min(R, G, B);
const l = (max + min) / 2;
const d = max - min;
let h = 0;
let s = 0;
if (d !== 0) {
s = d / (1 - Math.abs(2 * l - 1));
if (max === R) h = 60 * (((G - B) / d) % 6);
else if (max === G) h = 60 * ((B - R) / d + 2);
else h = 60 * ((R - G) / d + 4);
}
if (h < 0) h += 360;
return { h: +h.toFixed(1), s: +(s * 100).toFixed(1), l: +(l * 100).toFixed(1) };
}
for (const hex of ["#ff8800", "#f80", "#4f46e5", "#ff880080"]) {
const rgb = hexToRgb(hex);
const { h, s, l } = rgbToHsl(rgb);
const alpha = rgb.a < 1 ? ` / ${+rgb.a.toFixed(2)}` : "";
console.log(hex, `rgb(${rgb.r} ${rgb.g} ${rgb.b}${alpha})`, `hsl(${h} ${s}% ${l}%${alpha})`);
}
#ff8800 rgb(255 136 0) hsl(32 100% 50%)
#f80 rgb(255 136 0) hsl(32 100% 50%)
#4f46e5 rgb(79 70 229) hsl(243.4 75.4% 58.6%)
#ff880080 rgb(255 136 0 / 0.5) hsl(32 100% 50% / 0.5)
HSL values are usually rounded, and rounding loses a little precision: hsl(243.4 75.4% 58.6%) converts back to #4f46e5 exactly, but the whole-number version hsl(243 75% 59%) gives #5048e5. When an exact match matters, keep the hex or rgb() value as the source of truth. For quick conversions, the Color Converter turns hex, rgb() and hsl() into each other and shows a swatch.
Other ways to write colors
- Named colors such as
rebeccapurpleortomato: fine for prototypes, but there are only about 150 of them. transparent, andcurrentColor, which means "the current text color" and is handy for borders and icons that should follow the text.oklch()andoklab(): newer formats, supported across major browsers since 2023, designed so that equal changes in lightness look equally different to the eye. Useful for generating palettes; the formats above remain the everyday ones.
Colors in a stylesheet: custom properties and dark mode
Define each color once as a custom property and refer to it everywhere. Changing a theme, including a dark mode, then means changing a few lines:
:root {
--brand: #4f46e5; /* hex */
--brand-soft: rgb(79 70 229 / 15%); /* the same color at 15% opacity */
--text: hsl(220 15% 20%);
--surface: #ffffff;
}
@media (prefers-color-scheme: dark) {
:root {
--text: hsl(220 15% 90%);
--surface: hsl(220 15% 12%);
}
}
body {
color: var(--text);
background: var(--surface);
}
.button {
background: var(--brand);
color: #ffffff;
}
.button:hover {
background: hsl(243 75% 50%); /* same hue, a little darker */
}
.badge {
background: var(--brand-soft);
border: 1px solid currentColor; /* follows the text color */
}
Every text and background pair in this example passes the contrast check below in both light and dark mode. Changing any of them means checking again.
Contrast: make sure text is readable
A color that looks fine on your screen can be unreadable on a phone in sunlight or for someone with low vision. The WCAG 2.2 contrast requirement (success criterion 1.4.3, level AA) sets minimum contrast ratios between text and its background:
| What | Minimum (AA) |
|---|---|
| Normal text | 4.5:1 |
| Large text: at least 18 point (24 CSS pixels), or 14 point (about 18.66 CSS pixels) bold | 3:1 |
| User interface components (input borders, focus rings) and meaningful graphics, under criterion 1.4.11 | 3:1 |
The stricter AAA level asks for 7:1 for normal text and 4.5:1 for large text. The ratio runs from 1:1 (identical colors) to 21:1 (black on white). It is computed from each color's relative luminance, which weights green most and blue least because that is how sensitive our eyes are. The formula from WCAG, in JavaScript:
// WCAG 2 relative luminance of an sRGB color given as 0-255 values
function luminance(r, g, b) {
const [R, G, B] = [r, g, b].map((v) => {
const c = v / 255;
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * R + 0.7152 * G + 0.0722 * B;
}
function contrastRatio(rgb1, rgb2) {
const [hi, lo] = [luminance(...rgb1), luminance(...rgb2)].sort((a, b) => b - a);
return (hi + 0.05) / (lo + 0.05);
}
const white = [255, 255, 255];
const samples = { "#000000": [0, 0, 0], "#767676": [118, 118, 118],
"#777777": [119, 119, 119], "#ff8800": [255, 136, 0], "#4f46e5": [79, 70, 229] };
for (const [hex, rgb] of Object.entries(samples)) {
const ratio = contrastRatio(rgb, white);
const verdict = ratio >= 4.5 ? "AA for all text" : ratio >= 3 ? "AA large text only" : "fails AA";
console.log(`${hex} on white: ${ratio.toFixed(2)}:1 ${verdict}`);
}
#000000 on white: 21.00:1 AA for all text
#767676 on white: 4.54:1 AA for all text
#777777 on white: 4.48:1 AA large text only
#ff8800 on white: 2.39:1 fails AA
#4f46e5 on white: 6.29:1 AA for all text
Two results stand out. #767676 passes for normal text on white, while #777777, one step lighter and visually indistinguishable, does not. And bright orange #ff8800 fails as a text color on white even though it looks bold and vivid; it works as a background behind dark text instead. Do not judge contrast by eye: measure it, with a script like this, the contrast checker in your browser's developer tools, or an accessibility checker, every time a color pair changes.
Contrast is not the only requirement. Do not use color as the only way to convey information (a red border alone for an error): add text or an icon, so the message also reaches people who cannot tell the colors apart.
Common mistakes
- Writing a hex color without the
#, or with five or seven digits: the declaration is ignored. - Mixing comma and space syntax in one
rgb()orhsl(). - Setting a text color without a background color (or the reverse), so a user's or browser's default theme produces an unreadable pair.
- Placing text on images or gradients without checking contrast at the lightest point behind the text.
- Using opacity to lighten text: the result depends on whatever is behind it, so measure the color that is actually displayed.
Building a mockup to try colors on? The Lorem Ipsum Generator fills it with placeholder text; this guide to lorem ipsum explains when to replace it with real copy.