DEV Community

Esther M
Esther M

Posted on

27 4

How to Change Background Opacity without Affecting Text

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>
Enter fullscreen mode Exit fullscreen mode

CSS

.opacity {
    background: #03acf0;
    opacity: 0.5;
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

CSS

.opacity {
    background: rgba(3, 172, 240, 0.5);
}
Enter fullscreen mode Exit fullscreen mode

Day 2 #100daysofcode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
elementalsymmetry profile image
elementalsymmetry

Thank you. This is exactly what I was looking for.

Collapse
 
potatodev_ profile image
Alex R

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?

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay