具有z索引-1的元素在祖父母的div下

时间:2017-10-04 07:03:15

标签: html css css-position z-index absolute

z-index:-1置于绝对孩子中会使祖父母处于下方。如何让绝对孩子去父母div而不是祖父母div?

.grandparent{
  background:rgba(0, 128, 0, 0.89);
  width:500px;
}

.parent{
  position:relative;
  width:200px;
  height:200px;
  background:yellow;
}

.absolute-child{
  position:absolute;
  width:100px;
  height:100px;
  background:red;
  top:10px;
  right:-50px;
  z-index:-1;
}
 <div class="grandparent">
    <div class="parent">
      <div class="absolute-child"> absolute ch
      </div>
      <div class="siblings">siblings</div>
    </div>
 </div

1 个答案:

答案 0 :(得分:1)

这是您想要的,将position: relative;添加到granparent,以便z-index: 0;为它工作。

.grandparent{
  background:rgba(0, 128, 0, 0.89);
  width:500px;
      z-index: 0;
    position: relative;
}

.parent{
  position:relative;
  width:200px;
  height:200px;
  background:yellow;
}

.absolute-child{
    position: absolute;
    width: 100px;
    height: 100px;
    background: red;
    top: 10px;
    right: -50px;
    z-index: -1;
}
<div class="grandparent">
    <div class="parent">
      <div class="absolute-child"> absolute ch
      </div>
      <div class="siblings">siblings</div>
    </div>
 </div