Alpha transparency is a much easier way to make a background transparent than having to specify a whole bunch of cross browser CSS opacity statements and works in a wide variety of browsers, with the usual exception of Internet Explorer prior to version 9. If you are using the CSS3 PIE utility in your web project then there’s an easy way to use alpha transparency with CSS3 PIE.
What am I trying to achive?
I’ve used this technique myself for the top navigation of one of my websites where there’s a background image with navigation tabs on top. The website also uses border-radius which PIE also helps with, but I won’t include that in the example in this post.
The screenshot below shows an example of a background image with a transparent block on top with some text. The background image can be seen opaque through the block.
The HTML and CSS
In the above example, the HTML looks like this:
<div id="exampleContainer">
<div id="exampleTransparency">Example transparency</div>
</div>
The CSS looks like this:
#exampleContainer {
background: url(https://electrictoolbox.com/wp-content/uploads/running.jpg);
height: 97px;
width: 500px;
}
#exampleTransparency {
/* set background with alpha channel transparancy: 1st for IE no PIE, 2nd for IE PIE, 3rd for others */
background: rgb(95,83,75);
-pie-background: rgba(0,0,0,0.5);
background: rgba(0,0,0,0.5);
/* add PIE for IE < 9 */
behavior: url(https://electrictoolbox.com/examples/pie.htc);
/* IE needs position set to something other than the default for this to work */
position: relative;
/* other css settings for content */
color: white;
padding: 10px;
}
/* prevent IE9 using PIE */
:root *> #exampleTransparency {
behavior: none;
}
It’s fairly self explanatory but just a couple of points…
There are three declarations for the background. The first is the fallback which will show a solid background color if PIE doesn’t work (i.e. Javascript is switched off). The second is the declaration for PIE which will be ignored by all browsers other than IE using PIE. The third sets the background with alpha transparency. Browsers that don’t support this will ignore it and use the earlier declaration.
Obviously change the path for pie.htc to where you store it on your own site. It does need to have the full path to it, as I mentioned in my gotchas about PIE post.
And finally that odd looking declaration at the end prevents IE9 from using PIE at all; by doing this it ensures IE9 will not download the pie.htc file. I talked about this in an earlier post as well.
Browser support for alpha transparency
All modern browsers support alpha transparency:
- Chrome
- Firefox 3+
- IE9+
- Opera 10+
- Safari 3+
Working example
I have a working example available to view in a browser, which should look more or less exactly like the screenshot example in this post.