hguser
hguser

Reputation: 36038

set different opacity for nested elements

I want to make a win7 file exporlor-like effect: the title bar have a opacity less than 1, while the content have no opacity.

Then I tried to combine two elements together to make it:

<div id="outer" style="background-color:black;opacity:0.6;padding:30px;position:absolute;width:400px;height:400px;">
    <div id="inner" style="background-color:gray;opacity:1;height:100%;"></div>
</div>

I want to make the div#outer have a opacity of 0.8,then make the div#inner have no opacity(with opacity=1).

However it seems that this does not work. Since the opacity of div#outer will affect that of the div#inner.

Any ideas?

Upvotes: 7

Views: 5118

Answers (2)

Christophe
Christophe

Reputation: 28144

The inner div will inherit the opacity of its container.

A cross-browser workaround is to avoid nested elements and use absolute positioning instead. You can see an example here where opacity is applied to the background but the text has an opacity of 1: http://www.pathtosharepoint.com/Lists/May2010/calendar.aspx?CalendarDate=5%2F5%2F2010

Code sample (two span elements are placed side by side within the main span, the second one is the background that gets the opacity):

<span style="position:relative;display:inline-block;width:100%;height:100%;">
    <span style="width:100%;height:100%;display:inline-block;text-align:center;cursor:pointer;border:1px solid Red;position:absolute;color:Red;font-weight:bold;">
    11:00 AM  Image Capture &amp; ECM Using SharePoint
    </span>
    <span style="display:inline-block;width: 100%;height:100%;background-color:Red;text-align:center;border:1px solid;z-index:-1;filter:alpha(opacity=20);opacity:0.2;font-weight:bold;">
    11:00 AM Image Capture &amp; ECM Using SharePoint
    </span>
</span>

Upvotes: 0

w____
w____

Reputation: 3605

However it seems that this does not work. Since the opacity of div#outer will affect that of the div#inner.

Correct.


But if what you want is just a translucent background, setting RGBA color as background-color would meet the needs. Like this:

<div id="outer" style="background-color: rgba(0,0,0,0.6);padding:30px;position:absolute;width:400px;height:400px;">
    <div id="inner" style="background-color:gray;height:100%;"></div>
</div>

For more infomation, read MDN documents here: https://developer.mozilla.org/en-US/docs/CSS/color


For IE 7 support, I believe this(using generated background image files) is an acceptable solution.

Upvotes: 8

Related Questions