How to Convert RGB to HSL
Converting RGB to HSL (Hue, Saturation, Lightness) translates a machine-friendly color format into a human-friendly one. While RGB tells a screen exactly how much light to emit, HSL describes color in a way that makes sense to designers and artists.
Why Convert to HSL?
RGB is notoriously difficult to manipulate by hand. If you have a base color of rgb(52 152 219) and you want to make it 20% darker for a hover state, you have to do complex math across all three channels. In HSL, that same color is hsl(204deg 70% 53%). To make it darker, you simply lower the Lightness value to 33%.
The Conversion Math
To convert RGB to HSL, the RGB values (0-255) must first be normalized to a scale of 0 to 1. Then, we find the maximum and minimum values among the three channels.
- Lightness: This is the easiest part. It is simply the average of the highest and lowest RGB channels:
(max + min) / 2. - Saturation: If the max and min are the same, the color is a shade of gray, and saturation is 0. Otherwise, it is calculated based on the difference between the max and min, scaled by the lightness.
- Hue: The hue angle (0-360) is determined by which RGB channel is the strongest. If Red is highest, the hue is near 0°. If Green is highest, it's near 120°. If Blue is highest, it's near 240°.
Converting RGB to HSL in JavaScript
Here is the standard algorithm for converting RGB values into an HSL object:
function rgbToHsl(r, g, b) {
// Normalize RGB to 0-1
r /= 255; g /= 255; b /= 255;
let max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0; // achromatic (gray)
} else {
let d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return {
h: Math.round(h * 360),
s: Math.round(s * 100),
l: Math.round(l * 100)
};
}