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

前端 未结 2 1951
后悔当初
后悔当初 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: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;
    }

    verylongtext

    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;
    }

    verylongtext

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

提交回复
热议问题