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 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:
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:
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;
background: url(images/image.jpg) rgba(255,255,255,0.4);