HEX, RGB and HSL — How Color Codes Work
colorcssdesign
Web colors are usually written as HEX, RGB or HSL. All three describe the same underlying color, but each makes a different task easier.
HEX
HEX represents red, green and blue as two hexadecimal digits each. For example, #ff0000 is pure red. It is compact and common in CSS.
RGB
RGB uses three decimal values from 0 to 255. The same red is rgb(255, 0, 0). It is convenient when manipulating channels in code.
HSL
HSL describes a color by hue, saturation and lightness. Hue is an angle from 0 to 360, while saturation and lightness are percentages. HSL makes it easy to reason about "a darker version of this color".
Converting in code
JavaScript:
function hexToRgb(hex) {
const value = parseInt(hex.replace('#', ''), 16)
return [value >> 16, (value >> 8) & 255, value & 255]
}
console.log(hexToRgb('#ff8000'))
Python:
hex_value = 'ff8000'
r, g, b = int(hex_value[0:2], 16), int(hex_value[2:4], 16), int(hex_value[4:6], 16)
print((r, g, b))
PHP:
[$r, $g, $b] = sscanf('ff8000', '%02x%02x%02x');
echo "$r, $g, $b";
Common pitfalls
- Omitting the
#when pasting a HEX value. - Confusing HSL hue, which is degrees, with a 0 to 255 channel.
- Forgetting the alpha channel when a value includes transparency.
Frequently asked questions
- Which format should I use in CSS? Any work; pick whichever you find most readable for the task.
- Can I convert colors without uploading anything? Yes. Conversion is deterministic math and runs locally.
Need to convert between formats? Try the free Color Converter — HEX, RGB, HSL and CMYK, all in your browser.