Converting hex colors to RGB is a common task in web development, especially when it comes to creating custom color schemes. In this tutorial, we’ll show you how to convert hex to RGB in CSS.
Step 1: Understanding Hex and RGB
Before we begin, let’s briefly review what hex and RGB colors are. Hex colors are 6-digit codes that represent red, green, and blue values (RRGGBB).
For example, #ff0000 is pure red.
RGB colors are defined using three integers that represent the amount of red, green, and blue in a color. RGB colors are usually expressed in this format: rgb(red, green, blue), where red, green, and blue are values between 0 and 255.
Step 2: Converting Hex to RGB
Now that we have a basic understanding of hex and RGB colors, let’s look at how to convert hex to RGB in CSS. There are a few ways to do this, but we’ll use the CSS function rgb().
To convert a hex color to RGB, we need to first separate the red, green, and blue values from the hex code. To do this, we can use substr() and parseInt() functions in CSS.
Here’s the formula to convert hex to RGB in CSS:
1 |
rgb(parseInt(hex.substring(0,2), 16), parseInt(hex.substring(2,4), 16), parseInt(hex.substring(4,6), 16)) |
Let’s break this formula down:
- parseInt(hex.substring(0,2), 16) takes the first two digits of the hex code and converts them to a decimal value (using a base of 16).
- parseInt(hex.substring(2,4), 16) takes the next two digits of the hex code and converts them to a decimal value.
- parseInt(hex.substring(4,6), 16) takes the last two digits of the hex code and converts them to a decimal value.
Step 3: Testing Hex to RGB Conversion
To test our hex to RGB conversion, let’s use an example hex code: #ff0000 (pure red).
Here is the code to convert #ff0000 to RGB in CSS:
1 |
background-color: rgb(parseInt("ff", 16), parseInt("00", 16), parseInt("00", 16)); |
The output of this code will be a red background color.
Here is the full code example:
1 2 3 4 |
/* Hex to RGB Example */ .hex-to-rgb { background-color: rgb(parseInt("ff", 16), parseInt("00", 16), parseInt("00", 16)); } |
.hex-to-rgb { background-color: rgb(255, 0, 0); }
And that’s it! You now know how to convert hex to RGB in CSS.
Note: Keep in mind that some CSS properties may require using the hex format instead of RGB, so it’s always a good idea to double-check which format is needed before converting.