Related to How do I give text or an image a transparent background using CSS?, but slightly different.
I'd like to know if it's possible to change the alpha value of a background image, rather than just the colour. Obviously I can just save the image with different alpha values, but I'd like to be able to adjust the alpha dynamically.
So far the best I've got is:
<div style="position: relative;"> <div style="position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; background-image: url(...); opacity: 0.5;"></div> <div style="position: relative; z-index: 1;"> <!-- Rest of content here --> </div> </div>
It works, but it's bulky and ugly, and messes things up in more complicated layouts.
There is no background-opacity property in CSS, but you can fake it by inserting a pseudo element with regular opacity the exact size of the element behind it.
First, we create a <div> element (class="background") with a background image, and a border. Then we create another <div> (class="transbox") inside the first <div>. The <div class="transbox"> have a background color, and a border - the div is transparent.
We can use this to add some white in front of the image. Unfortunately, we cannot simply specify a color, but we can specify a gradient. So if we specify a gradient with two times the same color and make that color slightly transparent using rgba , we can alter the color of an image.
For making it darker, we add linear-gradient(black,black). To sum it up : Use opacity and filter property to darken an image and create cool hover effect with it. Use RGBA colors to make your background image darker.
You can do the faded background with CSS Generated Content
Demo at http://jsfiddle.net/gaby/WktFm/508/
Html
<div class="container"> contents </div>
Css
.container{ position: relative; z-index:1; overflow:hidden; /*if you want to crop the image*/ } .container:before{ z-index:-1; position:absolute; left:0; top:0; content: url('path/to/image.ext'); opacity:0.4; }
But you cannot modify the opacity as we are not allowed to modify generated content..
You could manipulate it with classes and css events though (but not sure if it fits your needs)
for example
.container:hover:before{ opacity:1; }
UPDATE
You can use css transitions to animate the opacity (again through classes)
demo at http://jsfiddle.net/gaby/WktFm/507/
Adding
-webkit-transition: opacity 1s linear; -o-transition: opacity 1s linear; -moz-transition: opacity 1s linear; transition: opacity 1s linear;
to the .container:before
rule will make the opacity animate to 1 in one second.
Compatibility
.. so only the latest FF supports it for the moment.. but a nice idea, no ? :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With