Give a DIV a Transparent Background Color
DIV with a transparent background color
The age old question – how can I make my DIV a transparent background color?
So I’ve fielded two questions in the past week on WebDeveloper.com regarding this topic, so I figured I’d make a post about it.
I don’t know who exactly came up with this technique, and, honestly, I think I came up with this method myself when I was designing the first Horizon Conference website. You’ll notice the content area is transparent but the content isn’t! Here’s how to do it.
In the CSS spec, it states that child elements cannot have a higher opacity than the lowest opacity ancestor (actually I’ve paraphrased, but this is basically the idea). Unfortunately there’s no if’s and’s or but’s about, children of an element with an opacity of 0.8 can never have an opacity of anything higher than 0.8.
Fortunately, through the wonderful world of CSS positioning, just because elements look like children of a certain element, doesn’t mean that they are. Here’s the markup and CSS:
<div id="yourtransparentdiv"> <div class="bg"> </div> <h1>Your opaque heading</h1> <p>Your opaque content</p> </div>
#yourtransparentdiv {
position: relative;
}
div.bg {
background-color: #000;
width: 100%;
height: 100%;
top:0;
left:0;
position: absolute;
opacity: 0.8;
filter: alpha(opacity=80);
z-index: -1;
}
Voila! That’s it, that’s all there is to it, 100% cross-browser nothing more to it done. Easy, wasn’t it?
You can see the trick I’m sure: on the div that you want to have a transparent background – don’t actually set a transparency rule. Instead, make sure you put position: relative on it and inside place an empty, absolutely positioned div that is 100% width and height and is semi-transparent. You have to set the z-index to -1 to make sure the div.bg appears behind your content.
Remember, I don’t claim to have invented or named this technique, but this solution to transparent content was something that I did come up with myself at the time and didn’t come from Google.
Hope I’ve helped you out!