0

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>
Aruna
  • 11,959
  • 3
  • 28
  • 42
Harish
  • 1,193
  • 6
  • 22
  • 45
  • 2
    `background-color: rgba(rr, gg, bb, 0.5)`. –  Nov 17 '16 at 05:57
  • This question has already been asked [**Here**](http://stackoverflow.com/questions/16884398/how-to-change-the-background-colours-opacity-in-css). Before posting a question on SO try to fix it by yourself first or at least search on Google for it. I'm downvoting this question. – Mohammad Usman Nov 17 '16 at 06:09
  • Sorry, I didn't see that. I'll make sure that I do a proper research before asking a question next time. @MuhammadUsman – Harish Nov 17 '16 at 06:14

3 Answers3

3

Used RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity for a color.

RGBA Stand for (red, green, blue, alpha)

.main{
 background-color: rgba(255, 0, 0, 0.5); 
  width: 100%;
  height: 200px;
}
<div class="main">
  <p>Opacity of this text shouldn't be changed.</p>
</div>
Manish Patel
  • 3,648
  • 1
  • 14
  • 22
3

.main{
 background:rgba(220,0,0,0.2);
  width: 100%;
  height: 200px;
}
<div class="main">
  <p>Opacity of this text shouldn't be changed.</p>
</div>

You can use CSS like this.

.main{
 background:rgba(170,0,0,0.2);
  width: 100%;
  height: 200px;
}
ONE_FE
  • 968
  • 3
  • 19
  • 39
1

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>
Aruna
  • 11,959
  • 3
  • 28
  • 42
  • @Harish I updated your code, and you can execute it to see the effect. – Aruna Nov 17 '16 at 06:04
  • @Harish `Red` is having `255` as first argument and others as `0` and you can change the 4th parameter from `0-1` – Aruna Nov 17 '16 at 06:06