โ† Back to Blog

How to Convert RGB to HEX

2026-04-03 ยท 5 min read

โ† Back to Blog

How to Convert RGB to HEX

ยท 5 min read

When You Need to Convert RGB to HEX

Both CSS's rgb() function and HEX color codes are widely used in web development. When you obtain an RGB color value from a design tool like Sketch or Adobe XD but need to use HEX format in HTML attributes or legacy CSS, conversion becomes necessary. Additionally, some APIs and tools only accept HEX color input.

Manual Conversion Steps

Converting RGB to HEX involves converting each channel's decimal value to a two-character hexadecimal number. The steps are:

  1. Divide each decimal R, G, B value by 16 and record the quotient and remainder
  2. Convert the quotient and remainder to hex characters (10=A, 11=B, โ€ฆ, 15=F)
  3. Concatenate the three two-character groups and add the # prefix
RGB: rgb(255, 87, 51)

R = 255: 255 รท 16 = 15 rem 15 โ†’ FF
G = 87:   87 รท 16 = 5  rem 7  โ†’ 57
B = 51:   51 รท 16 = 3  rem 3  โ†’ 33

HEX: #FF5733

Handling Single-Digit Results

When a channel value converts to only a single hex digit (values 0โ€“15), you must pad it with a leading zero to maintain 2 characters. For example, RGB value 5 converts to hex 5, but in a HEX color code it must be written as 05, otherwise the color code will be invalid.

RGB: rgb(5, 16, 200)

R = 5:   5  โ†’ 05  (padded!)
G = 16:  16 โ†’ 10
B = 200: 200 รท 16 = 12 rem 8 โ†’ C8

HEX: #0510C8

JavaScript Implementation

In JavaScript, use Number.prototype.toString(16) to convert numbers to hex strings, and padStart to ensure two characters:

function rgbToHex(r, g, b) {
  const toHex = (n) => n.toString(16).padStart(2, '0').toUpperCase();
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}

// Usage
rgbToHex(255, 87, 51);  // '#FF5733'
rgbToHex(5, 16, 200);   // '#0510C8'
rgbToHex(0, 0, 0);      // '#000000'

Python Implementation

In Python, format strings make the conversion straightforward:

def rgb_to_hex(r, g, b):
    return '#{:02X}{:02X}{:02X}'.format(r, g, b)

# Usage
rgb_to_hex(255, 87, 51)  # '#FF5733'
rgb_to_hex(5, 16, 200)   # '#0510C8'

The {:02X} format specifier means: convert to uppercase hexadecimal (X), at least 2 characters wide, padded with zeros on the left (02).

Converting RGBA to HEX with Transparency

If your color includes transparency like rgba(255, 87, 51, 0.5), multiply the alpha value (0โ€“1) by 255, convert it to hexadecimal, and append it to the HEX string to form an 8-character HEX code:

function rgbaToHex(r, g, b, a) {
  const toHex = (n) => Math.round(n).toString(16).padStart(2, '0').toUpperCase();
  return `#${toHex(r)}${toHex(g)}${toHex(b)}${toHex(a * 255)}`;
}

rgbaToHex(255, 87, 51, 0.5); // '#FF573380'

Common Errors and Considerations

Try the online tool now โ€” no installation, completely free.

Open Tool โ†’

Try the free tool now

Use Free Tool โ†’