How to Change Background Opacity without Affecting Text in CSS?

This div has a transparent background.

When we change the opacity of an element, it affects the whole element i.e. the background as well as the text. Also, in CSS there is no such property as background-opacity that can change the opacity of the background without affecting the text.

In such situations where we want to change the transparency level of the element’s background without affecting its text, we can use CSS RGBA color format to change the background color of the element.

In RGBA format, we have an extra parameter that defines the transparency on a scale of 0 to 1. Here, 0 denotes 100% transparency and 1 denotes no transparency at all. The default value is 1.

In the following example, we have changed the opacity of the div element’s background to 0.4 without affecting its text:


    background: url(images/sand.jpg);
    background-color: rgba(0, 255, 0, 0.4);
    padding: 20px;