Hex, rgb and hsl colors in CSS
22 Four ways to write a colour
easyWrite the same blue as a hex value and as rgb, pick a related shade with hsl, and add a translucent overlay with an alpha channel. Convert the hex to its channels in the checks.
Stuck? Three hints, smallest first
- 1. Hex pairs are red, green and blue in base 16:
#3055d8is 48, 85, 216. - 2.
hsltakes a hue in degrees, then saturation and lightness as percentages. Changing lightness alone gives a matching shade. - 3. Modern syntax puts alpha after a slash:
rgb(23 23 26 / 55%). The comma form still works.
<div class="swatch hex">#3055d8</div>
<div class="swatch rgb">rgb(48 85 216)</div>
<div class="swatch hsl">hsl(226 68% 40%)</div>
<div class="swatch veil">alpha over the blue</div>
.swatch {
padding: 10px 12px;
margin-bottom: 6px;
border-radius: 6px;
color: #ffffff;
font-size: 0.85rem;
}
.hex { background: #3055d8; }
.rgb { background: rgb(48 85 216); } /* the same colour, other notation */
.hsl { background: hsl(226 68% 40%); } /* same hue, darker */
/* A translucent layer over an opaque one. Alpha applies to this colour only,
unlike opacity, which fades the element and everything inside it. */
.veil {
background: rgb(48 85 216);
box-shadow: inset 0 0 0 999px rgb(23 23 26 / 55%);
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// Convert the hex the stylesheet uses into channels, and compare with the rgb().
const hex = /\.hex\s*\{\s*background:\s*#([0-9a-f]{6})/i.exec(css)[1];
const channels = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16));
const stated = (/rgb\((\d+) (\d+) (\d+)\)/.exec(css) || []).slice(1).map(Number);
test('the hex is #3055d8', hex.toLowerCase(), '3055d8');
test('which is 48, 85, 216', channels, [48, 85, 216]);
test('and the rgb() says the same thing', stated, channels);
test('hsl is used for a related shade', /hsl\(226 68% 40%\)/.test(css), true);
test('alpha is written with a slash', /\/\s*55%/.test(css), true);
test('opacity is NOT used, which would fade the text as well', /[^-]opacity\s*:/.test(css), false);
test('white on all four backgrounds, each of which clears AA', /color:\s*#ffffff/.test(css), true);
test('four swatches', countTag(html, 'div'), 4);
Output
Hex and rgb say the same thing in different bases, which the second and third checks prove by converting one into the other. hsl earns its place when you need a set of related colours: hold the hue, move the lightness, and you get a consistent scale instead of four hand-picked hex values that nearly match. The real distinction to hold on to is alpha versus opacity: alpha makes one colour translucent, opacity fades the whole element including its text, which is almost never what a designer meant.