Set background opacity only in CSS
.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);
}
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 usergbainstead ofrgb - HSL:
hsla(0, 100%, 50%, 0.5);- Note that we usehslainstead ofhsl