JS: Convert Color Names to RGB, and to HSL

By Xah Lee. Date: .

Convert Color Names to RGB

// 2026-07-16
// convert color names to rgb

function colorNameToRgb(colorName) {
 const el = document.createElement("div");
 el.style.color = colorName;
 document.body.appendChild(el);
 const rgb = window.getComputedStyle(el).color;
 document.body.removeChild(el);
 return rgb;
 // return
 // "rgb(255, 192, 203)"
}

colorNameToRgb("red");
// "rgb(255, 0, 0)"

colorNameToRgb("pink");
// "rgb(255, 192, 203)"

Convert Color Names to HSL

// 2026-07-16
// convert color names to hsl

function colorNameToHsl(name) {
 const el = document.createElement("div");
 el.style.color = name;
 document.body.appendChild(el);
 const rgb = getComputedStyle(el).color;
 document.body.removeChild(el);

 const [r, g, b] = rgb.match(/\d+/g).map(Number);
 let [h, s, l] = rgbToHsl(r, g, b);
 return `hsl(${Math.round(h)} ${Math.round(s)}% ${Math.round(l)}%)`;
}

function rgbToHsl(r, g, b) {
 r /= 255;
 g /= 255;
 b /= 255;
 const 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;
 } else {
  const 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 * 360, s * 100, l * 100];
}

// Usage examples:

console.log(colorNameToHsl("red"));
// "hsl(0 100% 50%)"

console.log(colorNameToHsl("pink"));
// "hsl(350 100% 88%)"

CSS Color