你如何获得一个职位:绝对;位置上方的元素:相对;一

时间:2017-06-06 03:13:25

标签: html css css3

您可以在this fiddle中看到问题。

我有一个绝对定位的元素,其z-index为2,相对定位的元素的z-index为1.相对定位的元素包含绝对定位的元素。我认为z-index:2元素会显示在z-index上面:1个项目,但事实并非如此。有没有办法解决这个问题,以便z-index:2个项目首先是z-index:1个项目?



div {
  background: green;
  position: relative;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

<div>
  Row 1
  <span>I thought this would show above 'Row 2'</span>
</div>
<div>
  Row 2
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:5)

当您将z-index添加到位于父元素中但又有z-index的子元素时,父级z-index会启动新的堆叠顺序,而子级z-index 1}}是相对于父亲的z-index。因此,在这种情况下,z-index: 2仅与z-index: 1的父级内部的其他元素进行比较。要解决此问题,您可以将z-index应用于span,或者不要将最后divz-index

您可以在此处详细了解https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

body {
  font-family: arial;
}

* {
  padding: 10px;
}

div {
  background: green;
  position: relative;
  width: 100%;
  
}

div:first-child {
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
  display: inline-block;
}
<div>
  Row 1
  <span>
  I thought this would show above 'Row 2'
</span>
</div>
<div>
  Row 2
</div>

答案 1 :(得分:0)

问题是因为具有绝对位置的div与第二行无关。我在两个div周围添加了一个包装器并向其添加了position: relative;

.wrapper div {
  background: green;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

.wrapper {
  position: relative;
}
<div class="wrapper">
  <div>
    Row 1
    <span>I thought this would show above 'Row 2'</span>
  </div>
  <div>
    Row 2
  </div>
</div>

答案 2 :(得分:0)

只需删除z-index:1

&#13;
&#13;
div {
  background: green;
  position: relative;
  width: 100%;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}
&#13;
<div>
  Row 1
  <span>I thought this would show above 'Row 2'</span>
</div>
<div>
  Row 2
</div>
&#13;
&#13;
&#13;