DevToolBoxZA DARMO
Blog

Konwerter Hex na RGB: Przewodnik kodów kolorów dla programistów

8 min czytaniaby DevToolBox

Colors are the building blocks of every user interface, and developers constantly switch between hex color codes and RGB values. Whether you are styling a website with CSS, building a mobile app, or writing a data visualization script in Python, understanding how to convert between hex and RGB is essential. This complete guide explains the conversion algorithm, provides code examples in multiple languages, and covers advanced topics like alpha transparency.

Try our free online Hex to RGB Converter tool instantly.

What Are Hex Color Codes and RGB Values?

Hex color codes (also called hexadecimal colors) represent colors using a six-character string prefixed with #. Each pair of characters encodes one color channel: red, green, and blue. The format is #RRGGBB, where each pair is a hexadecimal number from 00 to FF (0 to 255 in decimal). For example, #FF5733 means red=255, green=87, blue=51. CSS also supports a three-character shorthand like #F00 which expands to #FF0000.

RGB values define colors using three decimal numbers representing red, green, and blue intensity, each ranging from 0 to 255. In CSS, you write rgb(255, 87, 51). RGB is widely used in CSS, JavaScript canvas APIs, image processing libraries, and display technologies. Both hex and RGB describe the same color space (sRGB), so conversion between them is lossless.

How Hex-to-RGB Conversion Works

The conversion from hex to RGB is straightforward because each hex pair directly maps to one RGB channel. Here is the step-by-step algorithm:

  1. Remove the # prefix if present.
  2. Handle shorthand: if the string has 3 characters (e.g. F0A), expand each character by doubling it (FF00AA).
  3. Split into pairs: take characters 1-2 as Red, 3-4 as Green, 5-6 as Blue.
  4. Convert each pair from hexadecimal to decimal: use parseInt(pair, 16) in JavaScript or int(pair, 16) in Python.

For example, converting #1A2B3C: Red = 1A = 1*16+10 = 26, Green = 2B = 2*16+11 = 43, Blue = 3C = 3*16+12 = 60. The result is rgb(26, 43, 60).

The reverse conversion (RGB to hex) works by converting each decimal channel value to a two-digit hexadecimal string and concatenating them: # + red.toString(16) + green.toString(16) + blue.toString(16), padding each with a leading zero if needed.

Common Hex Color Codes and Their RGB Values

Here is a quick reference table of commonly used colors with their hex and RGB equivalents:

ColorHexRGBPreview
Red#FF0000rgb(255, 0, 0)
Green#00FF00rgb(0, 255, 0)
Blue#0000FFrgb(0, 0, 255)
White#FFFFFFrgb(255, 255, 255)
Black#000000rgb(0, 0, 0)
Yellow#FFFF00rgb(255, 255, 0)
Cyan#00FFFFrgb(0, 255, 255)
Magenta#FF00FFrgb(255, 0, 255)
Orange#FF8000rgb(255, 128, 0)
Purple#800080rgb(128, 0, 128)
Coral#FF7F50rgb(255, 127, 80)
Teal#008080rgb(0, 128, 128)
Navy#000080rgb(0, 0, 128)
Gray#808080rgb(128, 128, 128)
Tailwind Blue 500#3B82F6rgb(59, 130, 246)

When to Use Hex vs RGB vs HSL

All three formats describe the same sRGB color space, but each has strengths for different workflows:

Hex (#RRGGBB) is the most compact format and the default choice in most CSS codebases. Design tools like Figma, Sketch, and Adobe XD copy colors as hex by default. Hex is ideal for static color definitions, style guides, and brand color documentation. Shorthand (#FFF) saves characters in stylesheets.

RGB / RGBA is the best choice when you need to manipulate individual color channels programmatically or when you need alpha transparency. Functions like rgba(0, 0, 0, 0.5) are the standard way to add opacity in CSS. RGB is also the native format for the HTML Canvas API, WebGL, and most image processing libraries.

HSL / HSLA (Hue, Saturation, Lightness) is the most human-readable format. It is excellent for creating color palettes, generating shades and tints (by adjusting lightness), and implementing dark mode themes. CSS custom properties with HSL make it easy to adjust colors dynamically: hsl(220, 90%, 56%) clearly communicates the color intent.

In practice, most developers use hex for static colors, rgba() for transparency, and hsl() for dynamic color systems. Modern CSS also supports the color() function and wide-gamut color spaces like Display P3, but hex and RGB remain the most widely supported.

Hex to RGB Conversion in JavaScript, CSS, and Python

JavaScript / TypeScript

Here is a robust hex-to-RGB function that handles 3-character shorthand, 6-character, and 8-character (with alpha) hex codes:

function hexToRgb(hex) {
  // Remove # if present
  hex = hex.replace(/^#/, '');

  // Handle 3-character shorthand (#F0A -> FF00AA)
  if (hex.length === 3) {
    hex = hex.split('').map(c => c + c).join('');
  }

  // Handle 4-character shorthand (#F0A8 -> FF00AA88)
  if (hex.length === 4) {
    hex = hex.split('').map(c => c + c).join('');
  }

  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);

  // Handle 8-character hex with alpha (#RRGGBBAA)
  if (hex.length === 8) {
    const a = parseInt(hex.substring(6, 8), 16) / 255;
    return { r, g, b, a: Math.round(a * 100) / 100 };
  }

  return { r, g, b };
}

// Examples
hexToRgb('#FF5733');    // { r: 255, g: 87, b: 51 }
hexToRgb('#3B82F6');    // { r: 59, g: 130, b: 246 }
hexToRgb('#F00');       // { r: 255, g: 0, b: 0 }
hexToRgb('#FF000080');  // { r: 255, g: 0, b: 0, a: 0.5 }

CSS: Hex vs RGB in Practice

In CSS, both hex and RGB are interchangeable. Modern browsers support both formats equally:

/* These produce the exact same color */
.element-hex   { color: #3B82F6; }
.element-rgb   { color: rgb(59, 130, 246); }

/* Transparency — both are equivalent */
.overlay-hex   { background: #3B82F680; }      /* 50% opacity */
.overlay-rgba  { background: rgba(59, 130, 246, 0.5); }

/* Modern CSS space-separated syntax */
.modern        { color: rgb(59 130 246); }
.modern-alpha  { color: rgb(59 130 246 / 0.5); }

/* CSS custom properties work with any format */
:root {
  --primary: #3B82F6;
  --primary-rgb: 59, 130, 246;
}
.card {
  background: rgba(var(--primary-rgb), 0.1);
  border: 1px solid var(--primary);
}

Python

Python makes hex-to-RGB conversion simple with built-in int() base conversion:

def hex_to_rgb(hex_color: str) -> tuple[int, int, int]:
    """Convert hex color string to RGB tuple."""
    hex_color = hex_color.lstrip('#')

    # Handle 3-character shorthand
    if len(hex_color) == 3:
        hex_color = ''.join(c * 2 for c in hex_color)

    r = int(hex_color[0:2], 16)
    g = int(hex_color[2:4], 16)
    b = int(hex_color[4:6], 16)

    return (r, g, b)


def rgb_to_hex(r: int, g: int, b: int) -> str:
    """Convert RGB values to hex color string."""
    return f'#{r:02x}{g:02x}{b:02x}'


# Examples
print(hex_to_rgb('#FF5733'))   # (255, 87, 51)
print(hex_to_rgb('#3B82F6'))   # (59, 130, 246)
print(hex_to_rgb('#F00'))      # (255, 0, 0)

print(rgb_to_hex(59, 130, 246))  # #3b82f6
print(rgb_to_hex(255, 87, 51))   # #ff5733

RGB to Hex (JavaScript)

The reverse conversion from RGB to hex is equally useful:

function rgbToHex(r, g, b) {
  return '#' + [r, g, b]
    .map(v => {
      const hex = v.toString(16);
      return hex.length === 1 ? '0' + hex : hex;
    })
    .join('');
}

// With alpha support
function rgbaToHex(r, g, b, a = 1) {
  const hex = rgbToHex(r, g, b);
  if (a === 1) return hex;
  const alphaHex = Math.round(a * 255).toString(16).padStart(2, '0');
  return hex + alphaHex;
}

// Examples
rgbToHex(255, 87, 51);        // '#ff5733'
rgbToHex(59, 130, 246);       // '#3b82f6'
rgbaToHex(255, 0, 0, 0.5);   // '#ff000080'

Alpha Channel: Hex with Transparency (#RRGGBBAA) and RGBA

Both hex and RGB support an alpha (opacity) channel. The alpha value controls transparency: 1.0 (or FF) means fully opaque and 0.0 (or 00) means fully transparent.

8-digit hex (#RRGGBBAA) appends a two-character alpha value after the color channels. For example, #FF000080 is red at 50% opacity (80 in hex = 128 in decimal, which is 128/255 = ~50%). Modern CSS supports this format in all major browsers (Chrome 62+, Firefox 49+, Safari 10+, Edge 79+). There is also a 4-character shorthand: #F008 expands to #FF000088.

rgba() is the more widely recognized syntax for transparent colors: rgba(255, 0, 0, 0.5). The fourth parameter is a decimal between 0 and 1. In modern CSS, you can also write rgb(255 0 0 / 0.5) using the space-separated syntax with a slash for alpha.

To convert the alpha channel between formats: hex to decimal: divide the hex value by 255 (e.g., 0x80 / 255 = 0.502). Decimal to hex: multiply by 255, round, and convert to hex (e.g., Math.round(0.5 * 255).toString(16) = "80").

/* Common alpha values: hex ↔ decimal */
100% opacity:  FF = 1.0    →  #FF0000FF  =  rgba(255, 0, 0, 1.0)
 90% opacity:  E6 = 0.9    →  #FF0000E6  =  rgba(255, 0, 0, 0.9)
 80% opacity:  CC = 0.8    →  #FF0000CC  =  rgba(255, 0, 0, 0.8)
 70% opacity:  B3 = 0.7    →  #FF0000B3  =  rgba(255, 0, 0, 0.7)
 60% opacity:  99 = 0.6    →  #FF000099  =  rgba(255, 0, 0, 0.6)
 50% opacity:  80 = 0.5    →  #FF000080  =  rgba(255, 0, 0, 0.5)
 40% opacity:  66 = 0.4    →  #FF000066  =  rgba(255, 0, 0, 0.4)
 30% opacity:  4D = 0.3    →  #FF00004D  =  rgba(255, 0, 0, 0.3)
 20% opacity:  33 = 0.2    →  #FF000033  =  rgba(255, 0, 0, 0.2)
 10% opacity:  1A = 0.1    →  #FF00001A  =  rgba(255, 0, 0, 0.1)
  0% opacity:  00 = 0.0    →  #FF000000  =  rgba(255, 0, 0, 0.0)

Frequently Asked Questions

How do I convert hex to RGB?

To convert a hex color code to RGB: (1) Remove the # prefix. (2) Split the 6-character string into three pairs of 2 characters each. (3) Convert each pair from hexadecimal to decimal using base-16 arithmetic. For example, #3B82F6 becomes R=59, G=130, B=246, which is rgb(59, 130, 246). For 3-character shorthand like #F0A, double each character first to get #FF00AA, then convert.

What is the difference between hex and RGB color codes?

Hex and RGB represent the same colors in the sRGB color space using different number systems. Hex uses base-16 (hexadecimal) notation in a compact 6-character string (#RRGGBB), while RGB uses three decimal numbers from 0-255. They are functionally identical: #FF0000 and rgb(255, 0, 0) are both pure red. Hex is more common in CSS and design tools, while RGB is preferred in programming contexts and when alpha transparency is needed (rgba).

Understanding hex and RGB color formats is a fundamental skill for web developers and designers. Whether you are hand-coding colors in CSS, manipulating pixel values in a canvas, or building a design system, the conversion between these formats is straightforward once you understand the hexadecimal number system. Bookmark this guide for reference, and use our tool for instant conversions.

Convert colors instantly with our free Hex to RGB Converter.

𝕏 Twitterin LinkedIn
Czy to było pomocne?

Bądź na bieżąco

Otrzymuj cotygodniowe porady i nowe narzędzia.

Bez spamu. Zrezygnuj kiedy chcesz.

Try These Related Tools

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

Related Articles

Przewodnik po gradientach CSS: Od podstaw do zaawansowanych technik

Opanuj gradienty CSS: liniowe, radialne, stożkowe, powtarzające z przykładami, efektami tekstu i optymalizacją.

CSS Text Gradient: Jak stworzyć tekst gradientowy w czystym CSS

Twórz tekst gradientowy za pomocą CSS i background-clip.