Z-index堆叠上下文

时间:2016-07-19 14:13:51

标签: html css z-index

我遇到了z-index不像听起来那么简单的问题。

在阅读了我发现的所有内容之后,我仍然无法找到解决方案。所以这是我的问题:

JSFiddle

<div id="first">
 <div id="middlelayer">
   2
 </div> 
</div>
<div id="second">
  <div id="toplayer">
    1
  </div>
  <div id="lowestlayer">
    3
  </div>
</div>

我希望不同父级(#middlelayer)的Div位于另外两个Div之间(#toplayer和#lowestlayer)。我基本上已经完成了z-indices的所有组合,并尝试了不透明度的变通方法:.99,如下所述:

https://philipwalton.com/articles/what-no-one-told-you-about-z-index/

到目前为止似乎没有任何工作,我希望你能帮助我。

非常感谢你!

3 个答案:

答案 0 :(得分:2)

.toplayer {
  width: 120px;
  background-color: green;
  position: fixed;
  z-index: 3;
}

#middlelayer {
  width: 140px;
  background-color: blue;
  position: fixed;
  z-index: 2;
}

#lowestlayer {
  width: 160px;
  background-color: yellow;
  position: fixed;
}
<div id="first" >      
        <div id="middlelayer">
          middle
        </div>
</div>
<div id="second">
  <div id="second2">
                <div id="lowestlayer">
                   low
                </div>       
                <div class="toplayer">
                    top                   
                </div>
  </div>
</div>

我刚刚向z-index:1添加了z-index:3到每个元素,它似乎产生了预期的效果。

编辑:

从我的回答中删除了JSFiddle,并将其替换为代码段。

答案 1 :(得分:1)

它似乎不是z-index问题,而是定位问题。由于您使用fixed定位,请记住元素相对于视口的位置。要将结果设置为top,将其设置为bottom,将最后一个(需要居中)设置为absolute centering

这是一个你可以在JSFiddle上看到的例子......

https://jsfiddle.net/kennethcss/smejLps4/

<强>更新

如果所需的结果只是简单地“分层”元素,您只需要像z-index那样应用...

JSFiddle

答案 2 :(得分:0)

我认为这就是你所需要的。请检查以下代码。

&#13;
&#13;
#lowestlayer {
  opacity: .99; 
}

#lowestlayer, #middlelayer, #toplayer {
  position: absolute;
  width: 100px;
  color: white;
  line-height: 100px;
  text-align: center;
}

#lowestlayer {
  z-index: 1;
  top: 20px;
  left: 20px;
  background: red;
  width: 200px;
  height: 200px;
}

#middlelayer {
  top: 45px;
  left: 45px;
  background: green;
  z-index: 2;
  width: 150px;
  height: 150px;
}

#toplayer {
  top: 70px;
  left: 70px;
  background: blue;
  z-index: 3;
  width: 100px;
  height: 100px;
}
&#13;
<div id="first">
 <div id="middlelayer">
   2
 </div> 
</div>
<div id="second">
  <div id="toplayer">
    1
  </div>
  <div id="lowestlayer">
    3
  </div>
</div>
&#13;
&#13;
&#13;