- Instant help with your CSS coding problems

Set background opacity only in CSS

Question:
How to set background opacity only in CSS?
Answer:
.bg-opacity {
    background-color: #ff000080;
}

/* -- OR with rgba -- */

.bg-opacity {
    background-color: rgba(255, 0, 0, 0.5);
}

/* -- OR with hsla -- */

.bg-opacity {
    background-color: hsla(0, 100%, 50%, 0.5);
}
Description:

Today's websites often require semi-transparent containers. Many people would automatically think of using the opacity property, but in most cases, it does not give the correct result. Opacity is not only applied to the background color, but also to all child elements. This causes contrast problems for text.

Fortunately, the solution is simpler than you might think. In CSS, colors can be specified in multiple ways. Hexadecimal #ff0000 , RGB rgb(255, 0, 0) or HSL hsl(0, 100%, 50%) . In each case, you can set the alpha channel value as an optional parameter to control transparency. 

That is, by setting the appropriate background-color property, you can make only the background color partially transparent:

  • Hexadecimal format: #ff000080;
  • RGB: rgba(255, 0, 0, 0.5); - Note that we use rgba instead of rgb
  • HSL: hsla(0, 100%, 50%, 0.5); - Note that we use hsla instead of hsl

 

Share "How to set background opacity only in CSS?"
Tags:
opacity, transparent, semi transparent, background, background color, css, alpha
Technical term:
Set background opacity only in CSS
Interesting things
OpanAi's ChatGPT