Proper use of opacity with nested DIVs? [duplicate

2019-04-25 02:56发布

问题:

This question already has an answer here:

  • Specify parent divs opacity but make it not affect children HTML elements 4 answers

So I'm trying to create a lightbox like feel. I created a #blackout div and an #enlargedBOX div.

The #blackout div has it's opacity set to 90%, because I want the background website to show through just a bit, however i do NOT want my #enlargedBOX div to use that same opacity. It seems that #blackout forces its own opacity onto anything within itself. How can i stop that?

<div id="blackout">
<div id="enlargedBOX">
        <img src="" width="500" height="500" border="0" />
    </div>
</div>

Here's a jsFiddle

You'll see that the RED background shows through on the white #enlargedBOX div.

回答1:

Just use rgba() - DEMO

#blackout {
    position:absolute;
    top:0px;
    left:0px;
    height:100%;
    width:100%;
    overflow:auto;
    z-index:100;
    background: rgba(0, 0, 0, .9);
}


回答2:

Take the enlargedBOX dialog div out from within the blackout background overlay div, and give it a higher z-index.

jsFiddle example

#enlargedBOX {
    position:relative;
    z-index:101;
    margin:50px auto;
    padding:0px;
    width:500px;
    height:500px;
    background:#FFF;
    opacity:1;
}

<div id="blackout"></div>
<div id="enlargedBOX">
    <img src="" width="500" height="500" border="0" />
</div>


标签: css opacity