How to set a transparent css background image opacity

This article was written by in December 13, 2013, & may not be posted on other sites!
Original source url for this article: How to set a transparent css background image opacity

How to set a transparent css background image opacity?
How do you set a css background image opacity to a div that doesn’t also affect it’s inner contents? Using only “opacity: 0.5;” will also fade all contents of the div by 50%. Well, there are some solutions to this!

How to set a transparent css background image opacity

 

 

How css opacity works

Basically you can set opacity to any element, 1 meaning 100% visible, and 0.4 meaning 40% visible. Here is a basic opacity example working in all browsers. It might look something like this:
.opacity{
filter:alpha(opacity=40);
-moz-opacity:0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
}

The problem with background image opacity:

So, You have a div with a css background-image set to it. But using the opacity property on the div will make the whole div and it’s contents / child elements transparent. How do you target only the div background image, not the inner contents?

 

Solutions to background image opacity:

Solution 1 – background image opacity

The quickest solution is to save the background image as a transparent png.

 

Solution 2 – background image opacity

You can put 2 separate divs on top of each other using “postition: absolute;” and “z-index” to controle the stack order. Set the background image opacity on the div at the bottom and let the div on top have full opacity holding the content. With two diffferent divs the css will not collide. Something like this:

#opacity-image-div-01{
position: absolute;
background: url(images/image.jpg);
height: 200px;
width: 200px;
opacity: 0.5;
}
#opacity-image-div-02{
position: absolute;
height: 200px;
width: 200px;
z-index: 100;
}

 

Solution 3 – background image opacity

Using the :after in the css will also fix the problem. Basically we have one div holding all the contents, and then using the :after to add empty content to be shown underneath using z-index: -1;

#opacity-div{
height: 200px;
width: 200px;
display: block;
position: relative;
}
#opacity-div:after{
background: url(images/image.jpg) rgba(255,255,255,0.4);
height: 200px;
width: 200px;
opacity: 0.5;
top: 0;
left: 0;
position: absolute;
z-index: -1;
content: "";
}

 

Complete code and download:

Spread the word

Facebooktwittergoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *