Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to change the opacity of an element's background using CSS?

Answer: Using background-color with RGBA colors

The opacity is a CSS property that adds a degree of transparency to the element. But adding the opacity directly to the element will affect the transparency of the child elements too. Further, there is no such property that can add opacity to the background of an element.

In this tutorial, we will be learning to add the opacity of an element's background without affecting the child element.

The RGBA colors are used to add Red-Green-Blue-Alpha colors. The alpha channel specifies the opacity of the color. These RGBA colors are added to make the background image transparent without affecting the child element.

Example: Change the opacity of background element

In this program, the opacity of the background element has been changed without affecting the child element.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
    body {
	  background-image: url("https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/user/profile/picture/iamabhishek1622449489_profile.png"); 
	  background-repeat: no-repeat;
	}
	.container{
	  width: 100%;
	  height: 500px;
	  background-color:rgba(255,255,255,.3);	  
    }	
</style>
</head>
<body>
    <div class="container">
	  <h2> The transparent background </h2>	
</body>
</html>

Output

Here is the output of the above program.

transparent background image

Example: Adding background color using RGBA color

We can create a transparent background by adding background color using RGBA colors. It will add color with the opacity value. The text element will not be affected. Here is a program to illustrate this.

Conclusion

In this tutorial, we have learned to add opacity to the background without affecting the child element. We can use RGBA colors to add a transparent image to the background or simply add a background color using RGBA colors. It is the most simple way to do so.



About the author: