Menu

HEX, RGB and HSL Colour Codes Explained (with JavaScript Converters)
📰

HEX, RGB and HSL Colour Codes Explained (with JavaScript Converters)

DEV Community: css·Usman Farooqi·about 7 hours ago
#GUiCHPbH
#devtocss#devto#dev#math#colour
Reading 0:00
15s threshold

A colour can be written in three common ways in CSS: HEX , RGB and HSL . They describe the same colour, so #ff8800 , rgb(255, 136, 0) and hsl(32, 100%, 50%) are exactly the same orange.

The three formats

Format Example How it works

HEX #ff8800 Red, green and blue as hexadecimal pairs

RGB rgb(255, 136, 0) Red, green, blue from 0 to 255

HSL hsl(32, 100%, 50%) Hue (0 to 360), saturation and lightness

Which one should you use?

All three work in CSS. HEX is the most common. HSL is the easiest to adjust by hand : keep the hue, then raise the lightness for a lighter shade or lower it for a darker one.

HEX to RGB in JavaScript

A HEX code is three bytes written in base 16. Short codes such as #09f expand to #0099ff .

function hexToRgb ( hex ) { hex = hex . replace ( '#' , '' ) ; if ( hex . length === 3 ) hex = [ . . . hex ] . map ( ( c ) => c + c ) .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.