Set Background Opacity in CSS

This tutorial will cover the different ways of setting the background opacity of HTML elements in CSS.

 

Set Opacity in CSS Using the opacity Property

The CSS opacity property controls other overall transparency of an HTML element, meaning it will affect both text and background visibility. The opacity values range from 0.0 (completely transparent) to 1 (no transparency.)

 

<button class="btn">Button</button>
.btn {
  background: #4296DC;
  opacity: 0.4;
}

 

Values such as 0.225 can be used for more precise opacity control.

 

Use the rgba() Function to Set CSS Background Opacity

To set only the background opacity of an HTML element, use the CSS rgba() function, which uses the red, green, blue, alpha model to make colors of varying transparency.

 

Here is an example of a button with a 50% transparent blue background applied with a CSS class containing the rgba() function:

 

<button class="btn">Button</button>
.btn {
  background: rgba(176,224,230, 0.5);
}

 

In the example above, the fourth argument of the rgba() function is the alpha channel, use to control the transparency, ranging from 0 to 1.

 

Set Transparency of Background Using HEX Values

Six-digit hex color values accept two numeric characters at the end to define the percentage of opacity – 00 fully transparent and 10 no transparency. Take the following example:

 

background: #4296DC;

 

To make the background 50% transparent, add 50 to the end of the hex code like this:

 

background: #4296DC50;