d
Amit DhamuSoftware Engineer
 

Using RGBa

2 minute read 00000 views

Using an RGB value as opposed to a hex value for your colours in CSS allows you to use opacity directly with the background colour or colour. This can be handy as CSS does not currently support a background-opacity property. This means that if you used the standard opacity property, it would alter the opacity of the entire element and all children within.

Example

If your CSS looked like this, you would have a div with a red background, black text and 50% opacity. The problem is that the opacity will also affect the text and not just the background:

div {
  background-color: #fe0000;
  color: #000000;
  opacity: 0.5;
}

Solution

div {
  background-color: rgba(255, 0, 0, 0.5);
  color: #000000;
}

Notice that we will still have a div with a red background with black text but notice the 0.5 added at the end of the RGB value. This represents the opacity of the background colour only.

For a more detailed look at this, check out this article at 24 ways.