Lower z-indexed parent's child upon higher z-indexed element?

前端 未结 2 1941
后悔当初
后悔当初 2020-12-06 22:49

Is there a way to manipulate the stacking context this way? I want the text to be on the top of the blue element.

相关标签:
2条回答
  • 2020-12-06 23:34

    It is unfortunately impossible to break the stacking context in this way, as a child's z-index is set to the same stacking index as its parent. You will need to make the text a sibling element, and additionally make sure it has a position other than static in order for the z-index to apply.

    From here, it's a simple matter of positioning it as desired (in this case with top: 150px and left: 150px.

    This can be seen in the following:

    div {
      width: 200px;
      height: 200px;
      position: absolute;
    }
    
    #a {
      z-index: 0;
      background-color: red;
      left: 150px;
      top: 150px;
    }
    
    #b {
      z-index: 1;
      background-color: blue;
      left: 0;
      top: 0;
    }
    
    p {
      position: absolute;
      z-index: 2;
      top: 150px;
      left: 150px;
    }
    <div id="a"></div>
    <div id="b"></div>
    <p>verylongtext</p>

    0 讨论(0)
  • 2020-12-06 23:36

    Yes you can, the trick is to keep the red element with z-index:auto so that p will not belong to its stacking context and can be placed above the blue element.

    auto

    The box does not establish a new local stacking context. The stack level of the generated box in the current stacking context is the same as its parent's box.ref

    Don't forget to make the p positioned in order to be able to use z-index:

    div {
      width: 200px;
      height: 200px;
      position: absolute;
    }
    
    #a {
      background-color: red;
      left: 150px;
      top: 150px;
    }
    
    #b {
      z-index: 1;
      background-color: blue;
      left: 0;
      top: 0;
    }
    
    p {
      z-index: 2;
      position: relative;
    }
    <div id="a">
      <p>verylongtext</p>
    </div>
    <div id="b"></div>

    You can also remove everything and play only with margin:

    div {
      width: 200px;
      height: 200px;
    }
    
    #a {
      background-color: red;
      margin-left: 150px;
      margin-top: 150px;
      overflow:hidden; /*remove margin-collapsing*/
    }
    
    #b {
      background-color: blue;
      margin-top: -350px;
    }
    <div id="a">
      <p>verylongtext</p>
    </div>
    <div id="b"></div>

    You can refer to this question ( Strange behavior of background when elements are overlapping) to understand how it works.

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