DevToolBoxGRATIS
Blog

Kleurconverter: RGB, HEX, HSL Complete Gids met Code Voorbeelden

14 min lezenby DevToolBox

Whether you are building a design system, debugging CSS, or translating a mockup into code, a reliable color converter is one of the most-used tools in a developer's toolkit. Converting between hex to rgb, rgb to hex, hsl to hex, and other formats is an everyday task that touches front-end styling, data visualization, accessibility auditing, and even back-end image processing. This comprehensive guide explains every major color model, walks through the math behind each conversion, provides copy-paste code snippets in JavaScript, Python, and Bash, and covers modern CSS color features like oklch() and color-mix(). If you need a quick color code converter, try our free online tool.

Try our free online Color Converter tool instantly.

Understanding Color Models: RGB, HEX, HSL, HSV, and CMYK

RGB (Red, Green, Blue) is the foundational rgb color code model for screens. Every pixel on your monitor blends red, green, and blue light at intensities from 0 to 255. The notation rgb(255, 87, 51) means full red, moderate green, and low blue, producing a vivid orange. Because monitors emit light, RGB is an additive color model: mixing all three channels at maximum yields white. RGB is the native language of displays, the HTML Canvas API, WebGL shaders, and most image-processing libraries. Use RGB when you need precise channel-level control or when working directly with pixel data.

HEX (Hexadecimal) is the most common hex color code notation on the web. It is simply a compact representation of RGB values encoded in base-16. The color #FF5733 breaks down as FF = 255 red, 57 = 87 green, 33 = 51 blue, exactly the same orange as rgb(255, 87, 51). HEX codes can be 3-digit shorthand (#F53), 6-digit standard (#FF5733), or 8-digit with alpha (#FF573380). Because HEX values are compact and unambiguous, they are the default format in CSS stylesheets, Figma, Sketch, and design tokens. Knowing how to convert hex to rgb and back is essential for every front-end developer.

HSL (Hue, Saturation, Lightness) was designed to be more intuitive for humans. Hue is a degree on the color wheel (0-360), saturation is a percentage of color intensity (0-100%), and lightness is a percentage from black (0%) through the pure color (50%) to white (100%). The notation hsl(14, 100%, 60%) describes our orange. HSL makes it trivial to create lighter or darker variants by adjusting the L channel, or to desaturate a color by lowering S. This is why rgb to hsl conversion is so popular in theming systems and design tools. CSS natively supports hsl(), making it a first-class citizen in stylesheets.

HSV / HSB (Hue, Saturation, Value / Brightness) is the model used by most color picker interfaces, including those in Photoshop, Figma, and the native OS pickers. It shares the hue wheel with HSL but replaces lightness with value (brightness). In HSV, S=0 gives you a gray and V=0 is always black, which maps naturally to the square picker where you drag horizontally for saturation and vertically for brightness. While CSS does not support HSV directly, understanding the difference between HSL and HSV avoids confusion when translating designs to code.

CMYK (Cyan, Magenta, Yellow, Key/Black) is a subtractive color model for print. Inks absorb light rather than emitting it, so mixing all inks at full intensity yields black (in theory). The Key channel adds pure black for deeper shadows and crisper text. CMYK is irrelevant for CSS but essential when generating PDFs, prepping files for offset printing, or working with libraries like ReportLab or wkhtmltopdf. Converting between RGB and CMYK requires an ICC color profile for accurate results; naive formula-based conversions are only approximations.

Color Model Comparison Table

The following table summarizes the key properties of each color model to help you choose the right format for your use case:

ModelFormatRangeUse CaseCSS SupportHuman-Readable
RGBrgb(R, G, B)0-255 per channelScreen display, Canvas, WebGLYesLow
HEX#RRGGBB00-FF per channelCSS, design tools, tokensYesLow
HSLhsl(H, S%, L%)H: 0-360, S/L: 0-100%Theming, shade generationYesHigh
HSV/HSBhsv(H, S%, V%)H: 0-360, S/V: 0-100%Color pickers (Photoshop, Figma)NoHigh
CMYKcmyk(C%, M%, Y%, K%)0-100% per channelPrint, PDF generationNoMedium
OKLCHoklch(L C H)L: 0-1, C: 0-0.4, H: 0-360Modern CSS, wide gamutYesHigh

How Color Conversion Works: The Math Behind HEX, RGB, HSL, and HSV

Every color code converter implements a set of well-known mathematical formulas. Understanding these formulas helps you debug edge cases, write your own converter, or verify that a library produces correct output. Below we walk through each conversion with concrete numbers.

HEX to RGB: A hex color code like #FF5733 is simply three pairs of hexadecimal digits. To convert hex to rgb, parse each pair independently: parseInt("FF", 16) = 255, parseInt("57", 16) = 87, parseInt("33", 16) = 51. The result is rgb(255, 87, 51). For 3-digit shorthand like #F53, double each digit first: FF, 55, 33. For 8-digit hex with alpha, the fourth pair (e.g., 80) converts to an alpha value between 0 and 1: parseInt("80", 16) / 255 β‰ˆ 0.502.

RGB to HEX: To convert rgb to hex, take each channel value (0-255), convert it to a two-digit hexadecimal string, and concatenate them with a leading #. For example, rgb(255, 87, 51) becomes # + ff + 57 + 33 = #ff5733. In JavaScript: (255).toString(16).padStart(2, "0") returns "ff". The padStart ensures values below 16 (like 0-15) get a leading zero.

RGB to HSL: Converting rgb to hsl involves several steps. First, normalize R, G, B to the 0-1 range by dividing each by 255. Find the maximum (Cmax) and minimum (Cmin) of the three channels, and compute the delta (Cmax - Cmin). Lightness = (Cmax + Cmin) / 2. Saturation depends on lightness: if delta is 0, saturation is 0; otherwise S = delta / (1 - |2L - 1|). Hue depends on which channel is maximum: if R is max, H = 60 * ((G-B)/delta mod 6); if G is max, H = 60 * ((B-R)/delta + 2); if B is max, H = 60 * ((R-G)/delta + 4). For our orange rgb(255, 87, 51), this yields approximately hsl(11, 100%, 60%).

HSL to HEX: To convert hsl to hex, first convert HSL to RGB using the reverse formula, then convert each RGB channel to hex. The HSL-to-RGB algorithm computes a chroma value C = (1 - |2L - 1|) * S, an intermediate value X = C * (1 - |(H/60) mod 2 - 1|), and a match value m = L - C/2. Based on which 60-degree sector of the hue wheel H falls in, you assign (R1, G1, B1) from combinations of C, X, and 0, then add m to each channel and scale to 0-255.

RGB to HSV: The hue calculation is identical to RGB-to-HSL. Value = Cmax. Saturation = delta / Cmax (or 0 if Cmax is 0). HSV is simpler than HSL because it does not involve the lightness averaging step. For rgb(255, 87, 51): V = 1.0 (255/255), S = (255-51)/255 β‰ˆ 0.8, H β‰ˆ 11 degrees.

HSL to HSV and vice versa: While both share the hue component, converting between saturation and lightness/value requires some algebra. The formulas are: V = L + S * min(L, 1-L); Sv = (V > 0) ? 2 * (1 - L/V) : 0. The reverse: L = V * (1 - Sv/2); Sl = (L > 0 and L < 1) ? (V - L) / min(L, 1-L) : 0. These formulas explain why the same numeric saturation value means different things in HSL and HSV.

Color Conversion Code Examples

JavaScript / CSS Color Conversion

JavaScript provides no built-in color converter, but CSS color functions and simple parsing make conversions straightforward. Below are reusable functions for hex to rgb, rgb to hex, and rgb to hsl conversions:

// ===== HEX to RGB =====
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('#FF5733'); // { r: 255, g: 87, b: 51 }

// ===== RGB to HEX =====
function rgbToHex(r, g, b) {
  return '#' + [r, g, b]
    .map(x => x.toString(16).padStart(2, '0'))
    .join('');
}
rgbToHex(255, 87, 51); // "#ff5733"

// ===== RGB to HSL =====
function rgbToHsl(r, g, b) {
  r /= 255; g /= 255; b /= 255;
  const max = Math.max(r, g, b), min = Math.min(r, g, b);
  const l = (max + min) / 2;
  if (max === min) return { h: 0, s: 0, l: Math.round(l * 100) };
  const d = max - min;
  const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  let h = 0;
  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)
  };
}
rgbToHsl(255, 87, 51); // { h: 11, s: 100, l: 60 }

// ===== HSL to RGB =====
function hslToRgb(h, s, l) {
  s /= 100; l /= 100;
  const c = (1 - Math.abs(2 * l - 1)) * s;
  const x = c * (1 - Math.abs((h / 60) % 2 - 1));
  const m = l - c / 2;
  let r = 0, g = 0, b = 0;
  if (h < 60)       { r = c; g = x; b = 0; }
  else if (h < 120) { r = x; g = c; b = 0; }
  else if (h < 180) { r = 0; g = c; b = x; }
  else if (h < 240) { r = 0; g = x; b = c; }
  else if (h < 300) { r = x; g = 0; b = c; }
  else              { r = c; g = 0; b = x; }
  return {
    r: Math.round((r + m) * 255),
    g: Math.round((g + m) * 255),
    b: Math.round((b + m) * 255)
  };
}
hslToRgb(11, 100, 60); // { r: 255, g: 87, b: 51 }

// ===== CSS native color parsing (modern browsers) =====
// Use CSS.supports() and getComputedStyle for runtime conversion
const el = document.createElement('div');
el.style.color = 'hsl(14 100% 60%)';
document.body.appendChild(el);
const rgb = getComputedStyle(el).color;
// "rgb(255, 87, 51)" - browser converts any format to RGB
document.body.removeChild(el);

Python Color Conversion

Python's standard library includes colorsys for HSL/HSV conversions, and third-party libraries like Pillow and matplotlib offer extended color handling:

import colorsys

# ===== RGB to HSL (colorsys uses HLS order) =====
r, g, b = 255, 87, 51
r_norm, g_norm, b_norm = r / 255, g / 255, b / 255
h, l, s = colorsys.rgb_to_hls(r_norm, g_norm, b_norm)
print(f"HSL: ({h*360:.0f}, {s*100:.0f}%, {l*100:.0f}%)")
# HSL: (11, 100%, 60%)

# ===== HSL to RGB =====
r2, g2, b2 = colorsys.hls_to_rgb(h, l, s)
print(f"RGB: ({r2*255:.0f}, {g2*255:.0f}, {b2*255:.0f})")
# RGB: (255, 87, 51)

# ===== RGB to HSV =====
h_hsv, s_hsv, v_hsv = colorsys.rgb_to_hsv(r_norm, g_norm, b_norm)
print(f"HSV: ({h_hsv*360:.0f}, {s_hsv*100:.0f}%, {v_hsv*100:.0f}%)")
# HSV: (11, 80%, 100%)

# ===== HEX to RGB =====
def hex_to_rgb(hex_color):
    hex_color = hex_color.lstrip('#')
    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))

print(hex_to_rgb("#FF5733"))  # (255, 87, 51)

# ===== RGB to HEX =====
def rgb_to_hex(r, g, b):
    return f"#{r:02x}{g:02x}{b:02x}"

print(rgb_to_hex(255, 87, 51))  # #ff5733

# ===== Using matplotlib colors =====
import matplotlib.colors as mcolors
rgb_tuple = mcolors.to_rgb('#FF5733')     # (1.0, 0.341, 0.2)
hex_value = mcolors.to_hex((1.0, 0.341, 0.2))  # '#ff5733'
rgba = mcolors.to_rgba('steelblue', alpha=0.5)

# ===== Using Pillow/PIL for image colors =====
from PIL import Image
img = Image.new('RGB', (1, 1), (255, 87, 51))
pixel = img.getpixel((0, 0))  # (255, 87, 51)
img_hsv = img.convert('HSV')   # Convert to HSV color space

Bash / CLI Color Conversion

Command-line tools like printf and ImageMagick's convert can handle basic color conversions directly in the terminal:

# ===== HEX to RGB using printf =====
hex="FF5733"
printf "RGB: %d, %d, %d\n" 0x${hex:0:2} 0x${hex:2:2} 0x${hex:4:2}
# RGB: 255, 87, 51

# ===== RGB to HEX using printf =====
r=255 g=87 b=51
printf "#%02x%02x%02x\n" $r $g $b
# #ff5733

# ===== ImageMagick color conversion =====
# Convert HEX to RGB
magick convert xc:"#FF5733" -format "%[fx:int(255*r)],%[fx:int(255*g)],%[fx:int(255*b)]" info:
# 255,87,51

# Get color info in multiple formats
magick convert xc:"#FF5733" -colorspace HSL -format "HSL: %[fx:r*360],%[fx:g*100]%%,%[fx:b*100]%%" info:

# ===== Convert named color to HEX =====
magick convert xc:"tomato" -format "#%02[hex:r]%02[hex:g]%02[hex:b]" info:
# #FF6347

# ===== Batch convert colors from file =====
# colors.txt: one hex color per line
while IFS= read -r color; do
  printf "%s -> RGB: %d, %d, %d\n" "$color" \
    0x${color:1:2} 0x${color:3:2} 0x${color:5:2}
done < colors.txt

Modern CSS Color Features

CSS has evolved far beyond basic rgb() and hsl(). Modern CSS supports perceptually uniform color spaces, wide-gamut colors, and powerful color manipulation functions:

/* ===== Modern CSS color syntax (no commas) ===== */
.element {
  /* RGB - modern space-separated */
  color: rgb(255 87 51);
  color: rgb(255 87 51 / 0.5);  /* with alpha */

  /* HSL - modern space-separated */
  background: hsl(14 100% 60%);
  background: hsl(14 100% 60% / 0.8);

  /* HWB - Hue, Whiteness, Blackness */
  border-color: hwb(14 0% 0%);        /* pure orange */
  border-color: hwb(14 20% 10%);      /* muted orange */
}

/* ===== OKLCH - perceptually uniform ===== */
.brand {
  --brand-primary: oklch(0.65 0.25 29);       /* vivid red-orange */
  --brand-light:   oklch(0.85 0.12 29);       /* light variant */
  --brand-dark:    oklch(0.45 0.20 29);       /* dark variant */
  /* Same hue, predictable lightness changes */
}

/* ===== color-mix() - blend colors ===== */
.mixed {
  background: color-mix(in oklch, #FF5733 70%, #3366FF);
  border: 1px solid color-mix(in srgb, currentColor 40%, transparent);
}

/* ===== Relative color syntax ===== */
.derived {
  --base: #FF5733;
  /* Lighten by increasing L in oklch */
  color: oklch(from var(--base) calc(l + 0.2) c h);
  /* Desaturate by reducing chroma */
  background: oklch(from var(--base) l calc(c * 0.5) h);
  /* Shift hue by 180 degrees (complementary) */
  border-color: hsl(from var(--base) calc(h + 180) s l);
}

/* ===== Wide gamut P3 colors ===== */
@supports (color: color(display-p3 1 0 0)) {
  .vivid {
    color: color(display-p3 1 0.3 0.1); /* more vivid than sRGB */
  }
}

/* ===== Dark mode with light-dark() ===== */
:root {
  color-scheme: light dark;
  --text: light-dark(#1a1a1a, #e5e5e5);
  --surface: light-dark(#ffffff, #121212);
}

/* ===== CSS custom properties for theming ===== */
:root {
  --color-primary-h: 14;
  --color-primary-s: 100%;
  --color-primary-l: 60%;
  --color-primary: hsl(
    var(--color-primary-h)
    var(--color-primary-s)
    var(--color-primary-l)
  );
  --color-primary-hover: hsl(
    var(--color-primary-h)
    var(--color-primary-s)
    calc(var(--color-primary-l) - 10%)
  );
}

CSS Color Functions Deep Dive

Modern CSS offers a rich set of color functions that every front-end developer should know. The classic rgb() function now accepts the modern space-separated syntax: rgb(255 87 51) or with alpha rgb(255 87 51 / 0.5). Similarly, hsl() uses hsl(14 100% 60%) without commas. The hwb() function (Hue, Whiteness, Blackness) is a more intuitive alternative: hwb(14 0% 0%) produces a saturated color while hwb(14 30% 20%) mixes in white and black.

The oklch() function represents a breakthrough for web color. Based on the Oklab perceptual color space, oklch(lightness chroma hue) ensures that colors with the same lightness value actually look equally bright to the human eye, unlike HSL where hsl(60, 100%, 50%) (yellow) appears far brighter than hsl(240, 100%, 50%) (blue). OKLCH also unlocks the P3 wide-gamut color space, producing more vivid colors on modern displays: oklch(0.7 0.25 29) is a vibrant red-orange that cannot be expressed in sRGB.

The color-mix() function blends two colors in any color space: color-mix(in oklch, red 70%, blue) mixes 70% red with 30% blue in the perceptually uniform OKLCH space. The color() function accesses named color spaces directly: color(display-p3 1 0.5 0) specifies an exact P3 color. Relative color syntax lets you derive new colors from existing ones: hsl(from var(--brand) h s calc(l + 20%)) creates a lighter variant of your brand color.

Other useful CSS color values include currentColor (inherits the current text color, great for SVG icons), transparent (fully transparent black), and CSS custom properties for theming: --color-primary: oklch(0.6 0.2 250). The light-dark() function automatically selects between two colors based on the user's color scheme preference: light-dark(#333, #eee).

Color Accessibility and Contrast

WCAG contrast ratios are the foundation of accessible color design. The Web Content Accessibility Guidelines define two conformance levels: AA requires a minimum contrast ratio of 4.5:1 for normal text and 3:1 for large text (18px bold or 24px regular). AAA requires 7:1 for normal text and 4.5:1 for large text. The contrast ratio is calculated using the relative luminance of each color: ratio = (L1 + 0.05) / (L2 + 0.05), where L1 is the lighter color. Relative luminance uses linearized sRGB values with the formula L = 0.2126*R + 0.7152*G + 0.0722*B.

Color blindness considerations: Approximately 8% of men and 0.5% of women have some form of color vision deficiency. The most common type is deuteranopia (red-green), followed by protanopia (red-green) and tritanopia (blue-yellow). Never rely on color alone to convey information; always pair color with text labels, icons, or patterns. Avoid problematic combinations like red/green, green/brown, blue/purple, and green/gray. Use a color picker with built-in color blindness simulation to test your palette.

Building accessible color palettes: Start with your brand color and generate shades that meet WCAG AA on both white and dark backgrounds. Use OKLCH or CIELAB for perceptually uniform shade generation rather than simple HSL lightness adjustments. Test every foreground/background combination with a contrast checker. Consider using CSS forced-colors media query for Windows High Contrast mode. The prefers-contrast media query lets you serve higher-contrast variants to users who request them.

Color Best Practices for Developers

Design tokens and CSS custom properties: Define your color palette as design tokens and map them to CSS custom properties. Use semantic naming like --color-text-primary, --color-surface-elevated, and --color-border-subtle rather than literal names like --blue-500. This decouples your design decisions from implementation, making theme changes trivial: a dark mode is just a new set of token values. Store tokens in a single source of truth (JSON, YAML, or a Figma plugin) and generate CSS, Tailwind config, iOS, and Android values from it.

Dark mode strategies: Simply inverting lightness is a common mistake that produces washed-out or garish results. Instead, design dark mode as a separate theme with its own carefully chosen palette. In OKLCH, you can systematically lower lightness and reduce chroma for dark backgrounds while increasing lightness for text. Use CSS prefers-color-scheme to detect the user's preference and color-scheme: light dark on the root to opt in to browser-level dark mode support for form controls and scrollbars.

Consistent color naming and usage: Adopt a naming convention for your color scale (e.g., 50, 100, 200 ... 900, 950) where lower numbers are lighter. Map these to semantic roles: --surface-default might be --gray-50 in light mode and --gray-900 in dark mode. Never use raw hex color code values or rgb color code values directly in component styles; always reference tokens. This discipline pays off when rebranding, supporting multiple themes, or scaling a design system across products.

Performance considerations: CSS custom properties are resolved at runtime, which is usually fine but can cause jank if hundreds of properties animate simultaneously. For animations, prefer oklch() interpolation over rgb() for smoother perceptual transitions. Precompute gradient stops rather than relying on color-mix() in tight animation loops. When converting colors server-side for image processing, use C/Rust libraries for hot paths rather than JavaScript/Python.

Frequently Asked Questions

How do I convert HEX to RGB and RGB to HEX?

To convert HEX to RGB, split the hex code into three pairs (e.g., #FF5733 becomes FF, 57, 33) and parse each pair as a base-16 integer: parseInt("FF", 16) = 255, parseInt("57", 16) = 87, parseInt("33", 16) = 51, giving rgb(255, 87, 51). To convert RGB to HEX, do the reverse: convert each channel to a 2-digit hex string with toString(16).padStart(2, "0") and concatenate them with a # prefix. For example, 255 = ff, 87 = 57, 51 = 33, so the result is #ff5733. Our online color converter tool performs these conversions instantly.

What is the best color format for web development?

For most web projects, HEX codes are the default because they are compact, widely supported, and used by design tools like Figma and Sketch. However, HSL is better for theming because you can easily adjust lightness and saturation to create variants. For modern browsers (2024+), oklch() is the best choice because it provides perceptually uniform colors and access to the wider P3 gamut. Use design tokens to store your canonical color values and generate whatever format each platform needs.

What are the WCAG color contrast requirements for accessibility?

WCAG 2.1 defines two levels: Level AA requires a contrast ratio of at least 4.5:1 for normal text (under 18px bold or 24px regular) and 3:1 for large text. Level AAA requires 7:1 for normal text and 4.5:1 for large text. The contrast ratio is calculated from the relative luminance of the foreground and background colors. Non-text elements like icons and UI controls require at least 3:1 contrast against adjacent colors. Always test with an automated contrast checker and manual screen reader testing.

Color conversion is a foundational skill that connects design tools, CSS authoring, accessibility, and back-end processing. Whether you need a quick hex to rgb lookup, a reliable color code converter for your build pipeline, or guidance on accessible palettes, this guide provides everything in one place. Bookmark it for reference and try our free tool for instant conversions.

Related: Read our in-depth guide on HEX to RGB conversion for additional conversion tips and examples.

Convert colors between HEX, RGB, HSL, and more with our free online Color Converter.

𝕏 Twitterin LinkedIn
Was dit nuttig?

Blijf op de hoogte

Ontvang wekelijkse dev-tips en nieuwe tools.

Geen spam. Altijd opzegbaar.

Try These Related Tools

🎨Color Converter🎨Hex to RGB Converter🎨Color Palette GeneratorTWTailwind CSS Color Picker

Related Articles

Hex naar RGB Converter: Kleurcode Gids voor Ontwikkelaars

Gratis hex naar RGB converter en gids. Leer hoe hex kleurcodes werken met voorbeelden in JavaScript, CSS en Python.

CSS Gradient Gids: Van basis tot geavanceerde technieken

Beheers CSS-gradiΓ«nten: lineair, radiaal, conisch, herhalend met voorbeelden, teksteffecten en performancetips.

CSS Variabelen (Custom Properties) Complete Gids

Beheers CSS custom properties. Syntaxis, scoping, fallback-waarden en dark mode theming.