Position an element under a div by using z-index

那年仲夏 提交于 2019-12-13 17:18:53

问题


I tried to put a child div that will come under its parent and over the other elements.

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

I want to position the red rectangle to be under the blue and over the yellow. I put the z-index on three of them. However, it doesn't work.

What do you think about this? Thanks!

Update: Although the boxes are in the right order, however, the elements inside those boxes cannot be clicked now.

You can take a look at the error here: https://jsfiddle.net/p1xd6zah/


回答1:


You can do a hack with z-index:

  1. You can add z-index: -1 to box2. (stacks the child below the parent)

  2. Add z-index: -2 and position: relative to box3 (now stack this behind box2)

Remove the z-index from box1 - see demo below:

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


来源:https://stackoverflow.com/questions/46200477/position-an-element-under-a-div-by-using-z-index

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