Posted By: Anonymous
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.
If the background doesn’t have to repeat, you can use the sprite technique (sliding-doors) where you put all the images with differing opacity into one (next to each other) and then just shift them around with
Or you could declare the same partially transparent background image more than once, if your target browser supports multiple backgrounds (Firefox 3.6+, Safari 1.0+, Chrome 1.3+, Opera 10.5+, Internet Explorer 9+). The opacity of those multiple images should add up, the more backgrounds you define.
This process of combining transparencies is called Alpha Blending and calculated as (thanks @IainFraser):
αᵣ = α₁ + α₂(1-α₁) where
α ranges between 0 and 1.