【问题标题】:Position an element under a div by using z-index使用 z-index 将元素定位在 div 下
【发布时间】:2017-09-13 23:37:00
【问题描述】:

我试图将一个子 div 放在其父元素之下和其他元素之上。

.box1{
  background-color: blue;
  width: 500px;
  height: 100px;
  position: relative;
  z-index: 3;
}

.box2{
  position: absolute;
  background-color: red;
  width: 200px;
  height: 100px;
  left: 30%;
  top: 20px;
  z-index: 2;
}

.box3{
  background-color: yellow;
  width: 500px;
  height: 100px;
  z-index: 1;
}
<div class="box1">
  <div class="box2"></div>
</div>
<div class="box3"></div>

我想将红色矩形定位在蓝色下方和黄色上方。我将 z-index 放在其中三个上。但是,它不起作用。

您对此有何看法?谢谢!

更新:虽然这些框的顺序正确,但是这些框内的元素现在无法点击。

您可以在这里查看错误:https://jsfiddle.net/p1xd6zah/

【问题讨论】:

  • 蓝色和黄色框有不同的stacking contexts。由于蓝色盒子的 z-index 为 3,黄色盒子的 z-index 为 1,因此无论内在的孩子(你可以将它设置为 1000,它不会改变任何东西)。将红色夹在两者之间的唯一方法是确保红色框是其他两个框的兄弟。

标签: html css css-position z-index


【解决方案1】:

您可以使用z-index 进行hack

  1. 您可以将z-index: -1 添加到box2。 (将 child 堆叠在 parent 下方)

  2. z-index: -2position: relative 添加到box3(现在将其放在box2 后面

box1 中删除z-index - 请参见下面的演示:

.box1 {
  background-color: blue;
  width: 500px;
  height: 100px;
  position: relative;
}

.box2 {
  position: absolute;
  background-color: red;
  width: 200px;
  height: 100px;
  left: 30%;
  top: 20px;
  z-index: -1;
}

.box3 {
  background-color: yellow;
  width: 500px;
  height: 100px;
  z-index: -2;
  position: relative;
}
<div class="box1">
  <div class="box2"></div>
</div>
<div class="box3"></div>

【讨论】:

  • 嗨 kukuz,还有一个问题,因为现在无法单击框内的元素。你能看一下吗? jsfiddle.net/p1xd6zah
  • 谢谢kukkuz,那我会找到另一个解决方案的。
猜你喜欢
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 2015-10-03
  • 2010-12-13
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
相关资源
最近更新 更多