CSS使用z-index将子级设置为最高

时间:2018-10-23 10:35:52

标签: css z-index

https://codepen.io/anon/pen/QZVVbY

我希望绿色框上方的代码位于最上方。

但是显然,它在另一个小的z-index容器下。

我不想更改父级z-index。如何实现呢?

  

不更改父级和其他父级的z-index

.container{
  width: 500px;
  height: 50px;
}

.container1 {
  background: red;
  width: 500px;
  height: 50px;
  position: relative;
  z-index: 2;
}
.container2 {
  background: blue;
  width: 50px;
  height: 50px;
  position: relative;
}
.container3 {
  background: green;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 30px;
  left: 20px;
  z-index: 2200000;
}
.container4 {
  background: yellow;
  width: 500px;
  height: 50px;
  position: absolute;
  top: 0;
  left: 20px;
  z-index: 5;
}
.container5 {
  background: gray;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 15px;
  left: 40px;
}
<div class="container1">
  <div class="container2"></div>
  <div class="container3"></div>
</div>

<div class="container4">
  <div class="container5"></div>
</div>

1 个答案:

答案 0 :(得分:0)

问题在于container1上有一个z索引正在创建一个图层堆栈。这导致所有具有z-index的子元素都相对于父级z-index。为了使这项工作有效,从container删除z-index样式将获得您想要的效果。

.container{
  width: 500px;
  height: 50px;
}

.container1 {
  background: red;
  width: 500px;
  height: 50px;
  position: relative;
}
.container2 {
  background: blue;
  width: 50px;
  height: 50px;
  position: relative;
}
.container3 {
  background: green;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 30px;
  left: 20px;
  z-index: 999999;
}
.container4 {
  background: yellow;
  width: 500px;
  height: 50px;
  position: absolute;
  top: 0;
  left: 20px;
  z-index: 5;
}
.container5 {
  background: gray;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 15px;
  left: 40px;
}
 
<div with z-index=1 class="container1" >
    <div class="container2"></div>
    <div with z-index=100 class="container3" ></div>
</div>

<div with z-index=2 class="container4" >
  <div class="container5"></div>
</div>