Create non-transparent div on top of transparent parent element

Payton Byrd picture Payton Byrd · Mar 1, 2010 · Viewed 67.4k times · Source

EDIT: Changed title to actually be correct

I'm trying to simulate a modal popup in all HTML and CSS and am having a bit of bad luck with one single element of what I'm doing. I want the innermost div, the one with the content, to not be opaque like the border is, but no matter what I try with the CSS I cannot get it to work. Here's the code:

The CSS

.modalBackground {
    background-color:Gray;
    filter:alpha(opacity=70);
    opacity:0.7;
}

The HTML

  <table style="height: 100%; width: 100%; position: fixed; top: 0; left: 0;"><tr><td class="modalBackground">
    <div style="display: table; height: 40px; width: 150px; position: fixed; overflow: hidden; 
        top: 40%; margin-top: -50px; left: 50%; margin-left: -75px; padding-left: 30px;
        border: solid 1px navy; background-color: White;">
        <div style="#position: absolute; #top: 50%; display: table-cell; vertical-align: middle;">
            <div style="#position: relative; #top: -50%;"
                ><asp:Image runat="server" ImageUrl= "~/images/indicators/indicatordark.gif" /> working...</div>
        </div>
    </div></td></tr></table>

I am reaching my witt's end on this. I'm no HTML or CSS guru by any means, so an explanation of why the solution works would be greatly appreciated.

Answer

user241244 picture user241244 · Mar 1, 2010

Updated Answer

The best way to do this now is to use rGBA colors. It won't work for older browsers, but you can let the design gracefully degrade by just feeding them a solid color. Example:

CSS

.parent {
    background: gray; /* older browsers */
    background: rgba(128,128,128,0.7); /* newer browsers */
}

.child {
    background: blue;
}

Original Answer

It is annoying, but CSS doesn't allow that. Setting opacity for one element means no child element can have any greater opacity. (100% of 25% opacity is? Right.)

So, one solution is to use a tiny transparent PNG as a repeating background image to work around that. The only issue there is IE6, and there's an excellent workaround called supersleight.

(Updated. Think supersleight will work for you.)

Update Here's a very simple test case. Create the image (say, a PNG with 50% black fill) and then create this file--save them in the same folder. If you don't see a thin box with a transparent background behind 'stuff', then you're either not saving the file correctly or have saved the image somewhere else.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<style type="text/css">
body { background:white; }
#overlay { background-image:url(test.png); }
</style>
</head>
<body>
<div id="overlay">stuff</div>
</body>
</html>