Z-Index with different parents

这一生的挚爱 提交于 2019-12-19 02:47:54

问题


I'm having some trouble with the z-index. This is my simplified layout:

<div id="overlapper"></div>
<div id="container">
    <div id="child1"></div>
    <div id="child2"></div>
</div>

I need overlapper to appear in front of child1 but behind child2. I tried messing around with z index but it didn't work, I think because of the stacking context.

Any help please? thanks


回答1:


First, make sure that overlapper, child1 and child2 belong to the same stacking context.

That is, make sure container doesn't create a stacking context:

  • container must not be the root element.
  • container must have the default value for position, z-index, opacity and isolation properties:
    • position: static or z-index: auto
    • opacity: 1
    • isolation: auto

Now, make overlapper, child1 and child2 positioned elements, and add z-index as you want.

#overlapper, #child1, #child2 {
  position: relative;
  padding: 30px;
  height: 20px;
}
#overlapper {
  z-index: 3;
  background: red;
  top: 60px;
  margin-left: 20px;
}
#container {
  margin-top: -40px;
}
#child1 {
  z-index: 2;
  background: green;
  top: -40px;
}
#child2 {
  z-index: 4;
  background: blue;
  margin-left: 40px;
}
<div id="overlapper">Overlapper</div>
<div id="container">
    <div id="child1">Child 1</div>
    <div id="child2">Child 2</div>
</div>



回答2:


HTML

<div id="overlapper"></div>
<div id="container">
    <div id="child1"></div>
    <div id="child2"></div>
</div>

CSS

#overlapper, #child1, #child2
{
    height: 100px;
    width: 100px;
    position: absolute;
}
#overlapper
{
    background: red;
    top : 40px;
    left : 40px;
    z-index: 1;
}
#child1
{
    background: yellow;
    z-index: 0;
}
#child2
{
    top: 60px;
    left : 60px;
    background: black; 
    z-index: 2;
}

Fidle Here



来源:https://stackoverflow.com/questions/27329962/z-index-with-different-parents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!