几个嵌套 div 上的 Z 索引和不透明度



我正在尝试一个简单的设计,其中包含三个嵌套的div(Div 3在Div 2内部,Div 1),每个div彼此重叠(Div 3覆盖在Div 2上,Div 1上覆盖)。中间的div(Div 2)具有一定程度的不透明度,因此最外面的div(Div 1)在某种程度上是可见的。但是,最顶层的div(即 Div 3)应该是完全可见的,并且 Div 2 的不透明度不应影响 Div 3。

这是jsfiddle。 孩子 2 的不透明度受到孩子 1 的不透明度的影响,我不想发生这种情况。我希望子项 2 的不透明度为 1.0。我该怎么做?请在Chrome和Firefox上进行测试。

以下是 html 部分:

    <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>

以下是css(注意我需要位置:两个孩子的绝对):

    .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;
      }

这是不可能的,不透明度会影响所有孩子。用

rgba(r,g,b,a) 

代替元素。

例:

.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;
}

看这里

打破嵌套div 的树:您不需要更改 HTML,而是将子div 中现在的背景颜色和不透明度设置为它的伪元素。

这样就可以打破不透明度通道中的依赖关系

    .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>

最新更新