Converting hex to RGB and RGB to hex

Published

Table of contents

Converting a Hex color to RGB

A Hex color is comprised of 6 numbers or letters prefixed by #, like so: #FFAA66. For those who do not know, these are hexadecimal values, and can range from 0 to F (from 0 to 15). In this context, we’ll be using them as three distinct values made up of two characters, giving us FF - AA - 66.

I’m not going to bore you too much with math but these values range from 0 to 255, with 00 being the minimum and FF being the maximum (15 * 16^0 +15 * 16^1 = 255).

What you’ll want to do then is get each of these elements and use the built-in parseInt Javascript function to parse them. This function takes a string as an input and tries to convert it into a number. We’ll be using the fact that it accepts a second argument representing the base the number we’re trying to parse uses. In this case, an hexadecimal is represented in base 16.

Once that’s done, we just need to output the converted values into a format acceptable by CSS, in this case rgb.

const hex = '#FDAADD'.substr(1);

const first = hex.substring(0, 2);
const second = hex.substring(2, 4);
const third = hex.substring(4);

const rgb = `rgb(${parseInt(first, 16)},${parseInt(second, 16)},${parseInt(third, 16)})`;

Check out your result with this little converter I’ve made 👇

RGB: rgb(253,170,221)

Converting a RGB color to Hex

This article wouldn’t be complete if we did not go the opposite direction by converting RGB to HEX.

We’re going to pretty much follow the same idea but in the other direction. Start by separating your RGB value into its three constituents. We’ll then want to use the built-in toString method of the Number type by once again specifying that we’re dealing in values that are base 16.

There’s a little trick to keep in mind: we expect every number to translate into two characters. We’ll be using the padStart method to add a ‘0’ whenever the the output does not give us two characters (like with 0).

let first = 255;
let second = 0;
let third = 100;

function RGBtoHex(decimals: numbers[]) {
	return `#${decimals.map((d) => d.toString(16).padStart(2, '0')).join('')}`;
}

const hex = RGBtoHex([first, second, third]);

I’ve made another little converter to showcase this stuff, just make sure not to go over 255 for any input

RGB
Hex: #ff0064

Dealing with RGBA, the RGB with opacity

The A stands for Alpha, think of it as a fancy way to say opacity. It’s actually pretty simple to deal with this as RGBA is an extention of a plain RGB color. Just switch rgb to rgba and add another number going from 0 to 1.0 representing the opacity you want your color to have. For example going from a pure red RGB to a half-transparent red RGBA would be:

rgb(255,0,0);
rgba(255,0,0,0.5);

It’s a little less known but HEX as well supports opacity. Just add the desired opacity in Hexadecimal to your Hex value. Following the similar red example from before would give us:

#FF0000;
#FF000080;
#utils