简体   繁体   中英

How do you add different opacities to nested items?

I have two nested items in HTML and I want to give the wrraping one opacity 0.8 and the one inside it opacity 1.
I think I understand why it does not work, but, how can I mimick that effect?
Here is a simplified HTML that shows the problem, I want the green square to be solid.

<div style='background-color:red;
            width: 500px;
            height: 500px;
            border: 1px solid black;
            position: absolute;
            top:0;
            left:0;
            opacity:0.8'>

    <div style='width:150px; height:150px; background-color:green; opacity:1'>
      Some content
    </div>
</div>

If you use the rgba CSS property instead of the opacity property you can achieve this:

<div style='background-color:rgba(0, 255, 0, 0.8) ;width: 500px; height: 500px; border: 1px solid black; position: absolute; top: 0; left: 0'>
<div style='position: relative; width: 150px; height: 150px; background-color: rgba(0, 0, 255, 1);'>aaaaaaaaa<br>aaaaaaaaa<br></div>
</div>

Demo: http://jsfiddle.net/ScHgC/

you could always embrace progressive enhancement and use rgba on your background-colors

// this will only affect the div it's applied to and not it's contents
background-color: rgba(0,0,0,0.8)

Using CSS2

I fiddled a demo for you that illustrates a key concept:

http://jsfiddle.net/audetwebdesign/pN69F/

You can start by adding a wrapper div to position your two enclosed div's, outer and inner . The outer comes before the inner , which means that the inner will sit over the outer (unless you adjust the z-index values).

You can set the opacity to the outer div and that will allow any background text or image to be partly visible. Set the opacity of the inner div to 1.0 to get fully saturated coloring.

I think most browsers support opacity, but check out http://www.quirksmode.org/css/opacity.html for vendor-specific CSS properties to handle IE quirks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM