简体   繁体   中英

Z-index and Opacity on several nested divs

I am trying to have a simple design with three nested divs (Div 3 inside Div 2 inside Div 1), each overlaid on top of each other (Div 3 overlaid on Div 2 overlaid on Div 1). The middle div (Div 2) has a certain level of opacity, such that the outermost div (Div 1) is visible to some extent. However, the div which is the top-most div (ie Div 3) should be completely visible and the opacity of Div 2 should not affect Div 3.

Here is the jsfiddle . Child 2's opacity is getting affected by Child 1's opacity, which I don't want to happen. I want Child 2's opacity to be 1.0. How can I do this? Please test on Chrome and Firefox.

Following is the html part:

    <html>
     <head>
     </head>
     <body>
       <div class="parent box">
         Parent
         <div class="child box">
           Child
           <div class="child2 box">
             Another Child
           </div>
        </div>
       </div>
     </body>
    </html>

Following is the css (note that I need position: absolute for both the children):

    .box{
         width:200px;
         height:200px;
     }

    .parent {
         background-color:green;  
    }

    .child {
         background-color:blue;
         left:40px;
         top:40px;
         z-index:10;
         position:absolute;
         opacity:0.35;
     }

     .child2 {
         background-color:green;
         left:40px;
         top:40px;
         z-index:100;
         position:absolute;
      }

That's not possible, opacity affects all childs. Use

rgba(r,g,b,a) 

for the elements instead.

Example:

.parent {
  background-color: rgba(28,179,239, 0.35)
}

.child {
  left:40px;
  top:40px;
  z-index:10;
  position:absolute;
  background-color: rgba(28,179,239, 0.5)
}

.child2 {
  background-color:green;
  left:40px;
  top:40px;
  z-index:100;
  position:absolute;
}

See here

Break the tree of the nested divs: You don't need to change your HTML, but set the background color and opacity that is now in the child div to a pseudo element of it.

This way you break the dependency in the opacity channel

  .box { width: 200px; height: 200px; } .parent { background-color: green; } .child { left: 40px; top: 40px; z-index: 10; position: absolute; } .child:after { content: ""; position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; background-color: blue; opacity: 0.35; } .child2 { background-color: green; left: 40px; top: 40px; z-index: 100; position: absolute; } 
 <div class="parent box"> Parent <div class="child box"> Child <div class="child2 box"> Another Child </div> </div> </div> 

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