Harish Harish - 23 days ago 6
HTML Question

Changing the opacity of background color of a div

I'm trying to create a div with a simple background color and some text on the div. I want to decrease the opacity of the background color of this div but when I do that the opacity of the text on the div is also getting changed. Is there a way to change the opacity of the background color only?



.main{
background-color: red;
width: 100%;
height: 200px;
opacity: 0.5;
}

<div class="main">
<p>Opacity of this text shouldn't be changed.</p>
</div>




Answer

You can use the alpha channel of the color as below which is a 4th argument in RGBA

rgba(255,0,0,0.1) /* 10% opaque red /
rgba(255,0,0,0.4) /
40% opaque red /
rgba(255,0,0,0.7) /
70% opaque red /
rgba(255,0,0, 1) /
full opaque red */

Note: Red will have 255 as first argument and others as 0 and you can change the 4th parameter from 0-1 for opacity

.main{
 background-color: rgba(255,0,0,0.7); 
  width: 100%;
  height: 200px;
  /*opacity: 0.5;*/
}
<div class="main">
  <p>Opacity of this text shouldn't be changed.</p>
</div>