DEV Community

arenasbob2024-cell
arenasbob2024-cell

Posted on • Originally published at viadreams.cc

HEX to RGB, HSL, CMYK: Color Conversion Made Simple

Working with colors across design tools, CSS, and print? Here's your complete guide to color format conversion.

Color Models Cheat Sheet

Format Example Use Case
HEX #FF6B35 CSS, web design
RGB rgb(255, 107, 53) CSS, screens
HSL hsl(19, 100%, 60%) CSS, color manipulation
HSV/HSB hsv(19, 79%, 100%) Design tools (Figma, Photoshop)
CMYK cmyk(0, 58, 79, 0) Print design

HEX to RGB Formula

function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

hexToRgb('#FF6B35'); // { r: 255, g: 107, b: 53 }
Enter fullscreen mode Exit fullscreen mode

RGB to HEX

function rgbToHex(r, g, b) {
  return '#' + [r, g, b]
    .map(x => x.toString(16).padStart(2, '0'))
    .join('');
}

rgbToHex(255, 107, 53); // "#ff6b35"
Enter fullscreen mode Exit fullscreen mode

RGB to HSL

function rgbToHsl(r, g, b) {
  r /= 255; g /= 255; b /= 255;
  const max = Math.max(r, g, b);
  const 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)) / 6; break;
      case g: h = ((b - r) / d + 2) / 6; break;
      case b: h = ((r - g) / d + 4) / 6; break;
    }
  }

  return {
    h: Math.round(h * 360),
    s: Math.round(s * 100),
    l: Math.round(l * 100)
  };
}
Enter fullscreen mode Exit fullscreen mode

CSS Color Functions (Modern)

/* Modern CSS color functions */
.element {
  /* Traditional */
  color: #FF6B35;
  color: rgb(255, 107, 53);
  color: hsl(19, 100%, 60%);

  /* Modern syntax (space-separated) */
  color: rgb(255 107 53);
  color: hsl(19 100% 60%);

  /* With alpha */
  color: rgb(255 107 53 / 0.5);
  color: hsl(19 100% 60% / 50%);

  /* Relative colors (new!) */
  color: hsl(from var(--brand) h s calc(l + 20%));
}
Enter fullscreen mode Exit fullscreen mode

WCAG Color Contrast

function getContrastRatio(color1, color2) {
  const l1 = getLuminance(color1);
  const l2 = getLuminance(color2);
  const lighter = Math.max(l1, l2);
  const darker = Math.min(l1, l2);
  return (lighter + 0.05) / (darker + 0.05);
}

// WCAG requirements:
// AA: 4.5:1 for normal text, 3:1 for large text
// AAA: 7:1 for normal text, 4.5:1 for large text
Enter fullscreen mode Exit fullscreen mode

Try It Online

Convert between HEX, RGB, HSL, HSV, and CMYK instantly with our free Color Converter — with live preview, contrast checker, and Tailwind CSS class matching.


What color format do you use most? Share in the comments!

Top comments (0)