css z-index issue with nested elements

前端 未结 2 1673
野的像风
野的像风 2020-11-27 23:36

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

相关标签:
2条回答
  • 2020-11-28 00:17

    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>

    0 讨论(0)
  • 2020-11-28 00:25

    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?

    0 讨论(0)
提交回复
热议问题