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:

Example:

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

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.