The Problem:
You can’t alter the opacity of a background image without affecting foreground content.
More precisely: If you want to alter the opacity of the background image of some element (say, a div), altering the opacity of that div will also effect all of its child elements — which is generally not what you’re looking for.
Like me, you may have learned this the hard way the first time you tried to add some heading text over a background image in a page hero.
Here’s what that attempt may have looked like. (Click on the HTML and CSS buttons to reveal and test the code of this CodePen pen.)
See the Pen
BG img in parent img; bg-color-alpha overlay in pseudo-element by Jeffrey Cohan (@jdcohan)
on CodePen.
Here’s the code for that (failed) hero element:
.hero {
position: relative;
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background-image: url("https://cdn.jeffcohan.com/Public/dolomites-background-image.jpg");
background-size: cover;
opacity: .45;
}
Jessica Chan (Coder Coder) Offers Two Solutions
Thanks to Jessica Chan (aka Coder Coder), we have two solutions to this problem, both of which she documented in this blog article and the first of which she demonstrated in this YouTube video. This post of mine is essentially a fork of her work.
Both solutions involve adding a pseudo element (::before) to the hero element. They differ in (a) where they put the background image and (b) how they set opacity/transparency.
Solution 1:
In this solution, the background-image and opacity properties are both added to parent’s pseudo-element. (Again, click on the HTML and CSS buttons to reveal and test the code of this CodePen pen.)
See the Pen
BG img in PSEUDO ELEMENT, with opacity by Jeffrey Cohan (@jdcohan)
on CodePen.
Solution 2:
In this solution, the background image is added to the parent; opacity/transparency is achieved by adding the background-color property — with an opacity/transparency value — to the parent’s pseudo-element.
See the Pen
BG img in parent img; bg-color-alpha overlay in pseudo-element by Jeffrey Cohan (@jdcohan)
on CodePen.
In Closing…
Check out other CSS-related blog articles, and let me know what you think in the comments section below. And do check out Coder Coder’s YouTube channel.
Like what you see? Share with others and join my mailing list. No long-term commitment, unsubscribe any time.

Leave a Reply