css z-index issue with nested elements

不打扰是莪最后的温柔 提交于 2019-12-17 05:14:25

问题


I have 3 HTML elements that I want to order on the z plane:

.bank {
  width: 200px;
  height: 200px;
  background-color: grey;
  position: absolute;
  
  z-index: 100;
  
  transform: translateY(10%);
}

.card {
  width: 100px;
  height: 100px;
  background-color: red;
  
  position: absolute;
  left: 50px;
  top: 50px;
  
  z-index: 300;
}

.button {
  width: 50px;
  height: 50px;
  background-color: green;
  
  position: absolute;
  left: 30px;
  top: 50px;
  
  z-index: 200;
}
<div class="bank">
       bank
       <div class="card">card</div>
    </div>
    
    <div class="button">button</div>

I want the button to be on top of the bank but behind the card. But the button is always on top of both the bank and the card no matter what I try.

Edit: I noticed that removing z-index and transform from '.bank' solves it, but I need the transform property. What can I do?

What may cause it not to work? Thanks


回答1:


Don't specify any z-index to .bank to avoid creating new stacking context and simply adjust the z-index of the other elements. This will work because all the 3 elements belong to the same stacking context so you can specify any order you want.

.bank {
  position:relative;
  background: red;
  width: 500px;
  height: 200px;
}

.card {
  position: absolute;
  top:0;
  z-index: 2;
  height: 100px;
  width: 400px;
  background: blue;
}

.button {
  position: absolute;
  top: 0;
  z-index: 1;
  height: 150px;
  width: 450px;
  background: yellow;
}

.container {
  position: relative;
}
<div class="container">
  <div class="bank">
    <div class="card"></div>
  </div>

  <div class="button"></div>
</div>

UPDATE

Considering you code, the only way is to remove the z-index and transform from .bank or it will be impossible because your elements will never belong to the same stacking context. As you can read in the previous link:

Each stacking context is self-contained: after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context.

Related for more details: Why can't an element with a z-index value cover its child?




回答2:


You can do this by adding z-index only to card class and placing the elements in absolute.

.bank {
  width: 150px;
  background: red;
  height: 150px;
  position: absolute;
  top: 0;
  left: 0;
}

.card {
  width: 50px;
  background: black;
  height: 50px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

.button {
  width: 100px;
  background: blue;
  height: 100px;
  position: absolute;
  top: 0;
  left: 0;
}
<div class="bank">
   <div class="card"></div>
</div>

<div class="button"></div>


来源:https://stackoverflow.com/questions/52074761/css-z-index-issue-with-nested-elements

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