How to Convert HSL to RGB
Converting HSL to RGB takes a color defined by human-friendly traits (Hue, Saturation, and Lightness) and translates it into the raw light intensities required by a digital screen.
Why Convert HSL to RGB?
While HSL is fantastic for building color palettes and adjusting shades on the fly, many older graphics libraries, canvas APIs, and legacy systems only understand RGB. Converting your HSL values ensures compatibility across the entire web stack.
The Mathematics of the Conversion
The conversion algorithm maps the HSL cylinder back into the RGB color cube. Here is how you can write this conversion in JavaScript:
function hslToRgb(h, s, l) {
// Normalize saturation and lightness to a 0-1 scale
s /= 100;
l /= 100;
// Helper function to calculate channel values
const k = n => (n + h / 30) % 12;
const a = s * Math.min(l, 1 - l);
const f = n =>
l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
// Return RGB values scaled to 0-255
return {
r: Math.round(255 * f(0)),
g: Math.round(255 * f(8)),
b: Math.round(255 * f(4))
};
}
// Example: hslToRgb(204, 70, 53) returns { r: 52, g: 152, b: 219 }
Modern CSS Syntax
If you are writing the converted RGB value back into a stylesheet, remember that modern CSS Color Module Level 4 prefers space-separated values over the legacy comma-separated format. For example, rgb(52 152 219) is preferred over rgb(52, 152, 219).