How to Convert RGB to HEX
Converting an RGB (Red, Green, Blue) color value into a HEX code is one of the most common tasks in web development. Both formats describe the exact same thing (how much red, green, and blue light a screen should emit) but they write it in different mathematical bases.
Base-10 vs. Base-16
RGB uses standard decimal (base-10) numbers, ranging from 0 to 255 for each channel. HEX uses hexadecimal (base-16) numbers, where the values range from 00 to FF.
To convert RGB to HEX, you simply take the decimal number for each channel and convert it into a two-digit hexadecimal string. Then, you concatenate them together with a # symbol at the front.
The Conversion Math
Let's convert the CSS color rgb(52 152 219) into HEX:
- Red (52): 52 ÷ 16 = 3 with a remainder of 4. In hex, this is
34. - Green (152): 152 ÷ 16 = 9 with a remainder of 8. In hex, this is
98. - Blue (219): 219 ÷ 16 = 13 with a remainder of 11. In hex, 13 is
Dand 11 isB, making itDB.
Combine them together, and you get #3498db.
Handling Alpha Transparency (RGBA to 8-Digit HEX)
If your RGB value includes an alpha channel for transparency, such as rgb(52 152 219 / 50%), you can convert it into an 8-digit HEX code. The alpha percentage (or decimal) is multiplied by 255 and converted to base-16 just like the color channels.
For 50% opacity: 0.5 × 255 = 127.5. Rounded to 128, the hex conversion is 80. Appending this to our color gives us #3498db80.
Converting RGB to HEX in JavaScript
JavaScript makes this conversion nice and easy using the toString(16) method on numbers. You just need to ensure that single-digit hex values are padded with a leading zero.
function rgbToHex(r, g, b) {
// Convert each channel to hex and pad with a leading zero if necessary
const toHex = (c) => {
const hex = c.toString(16);
return hex.length === 1 ? "0" + hex : hex;
};
return "#" + toHex(r) + toHex(g) + toHex(b);
}
// Example: rgbToHex(52, 152, 219) returns "#3498db"