Stacking order of elements affected by opacity

前端 未结 2 1048
时光取名叫无心
时光取名叫无心 2020-11-28 16:29

How are z-index and opacity related when deciding stacking order of an element in HTML?

when i keep opacity less than 1<

相关标签:
2条回答
  • 2020-11-28 16:57

    Positioned elements with a z-index value other than "auto" and elements with an opacity value less than 1 generate a stacking context. Refer to the rules regarding the painting order.

    In your first example we have the root stacking context with various descendants including:

    • positioned green box with positive z-index
    • positioned blue box with auto z-index

    The blue box with auto z-index is placed behind; green box with positive z-index is placed in front (see rule no. 8 and 9).

    In your second example we have:

    • an element with opacity (which contains green box; note that z-index on the green box becomes local to this element)
    • positioned blue box without z-index

    Both elements fall under same category (see rule no. 8). In which case the HTML order determines which element appear in front. The blue box appears later in the source order so it appears in front.

    0 讨论(0)
  • 2020-11-28 17:17

    Aside from the opacity stacking context Alexey Ten pointed out in his comment (which is a factor here), the z-index is relative to the element's container. In this case, both your blue and green elements are contained within separate div parents which have no defined z-index. Due to the HTML ordering, the latter div (the one with the blue box) will appear on top of the former one (the green one).

    In this below example, I've added the class .first to the first parent div and .second to the second one, then given them their own z-index properties.

    .green, .blue {
      position: absolute;
      width: 100px;
      color: white;
      line-height: 100px;
      text-align: center;
    }
    
    .green {
      z-index:999999999;
      top: 90px;
      left: 60px;
      background: green;
    }
    .gp{
      opacity:0.99;
    }
    .blue {
      top: 100px;
      left: 100px;
      background: blue;
    }
    
    .first, .second {
      position: relative;
    }
    
    .first {
      z-index: 2;
    }
    
    .second {
      z-index: 1;
    }
    <div class="first">
      <span class="green">Green</span>
    </div>
    <div class="second">
      <span class="blue">Blue</span>
    </div>

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