问题
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
:
You can add
z-index: -1
tobox2
. (stacks the child below the parent)Add
z-index: -2
andposition: relative
tobox3
(now stack this behindbox2
)
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