CSS can be tricky, and at times, frustrating to work with. One of the things I had trouble figuring out was how to change the opacity of a background without it also affecting the opacity of the text it contained.
For instance, let's say you have a parent div wrapped around some text and you wanted to change the opacity of just the div. You'd think that it'd be something as simple as the below.
HTML
<div class="opacity">
<p>Hello World!</p>
</div>
CSS
.opacity {
background: #03acf0;
opacity: 0.5;
}
However, if you've tried this, you probably found that it affects the opacity of whatever is nested within it as well. In this case, our text.
Well, here's a simple trick to help. There are other ways to work around this, but I've found this one to be the easiest.
Simply use rgba to define your background color and specify opacity with it at the same time by adjusting the last value, for alpha, in your rgba code.
For scaling, bringing the value closer to 0 increases transparency.
CSS
.opacity {
background: rgba(3, 172, 240, 0.5);
}
To simplify your HTML, you don't even need the parent div around your block of text to do this. Another way is to add the opacity class to whatever element you are working with.
HTML
<p class="opacity">Hello World!</p>
CSS
.opacity {
background: rgba(3, 172, 240, 0.5);
}
Day 2 #100daysofcode
Top comments (2)
Thank you. This is exactly what I was looking for.
Hii, this is for background color, but I have a background image so this setting won't work for me. Are there any other ways to do this same thing?