css z-index issue with nested elements

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

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

2条回答
  •  星月不相逢
    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;
    }

    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?

提交回复
热议问题