Why does z-index not work?

前端 未结 5 1504
无人共我
无人共我 2020-11-21 05:39

So if I understand z-index correctly, it would be perfect in this situation:

\"enter

5条回答
  •  無奈伤痛
    2020-11-21 06:24

    If you set position to other value than static but your element's z-index still doesn't seem to work, it may be that some parent element has z-index set.

    The stacking contexts have hierarchy, and each stacking context is considered in the stacking order of the parent's stacking context.

    So with following html

    div { border: 2px solid #000; width: 100px; height: 30px; margin: 10px; position: relative; background-color: #FFF; }
    #el3 { background-color: #F0F; width: 100px; height: 60px; top: -50px; }

    no matter how big the z-index of el3 will be set, it will always be under el1 because it's parent has lower stacking context. You can imagine stacking order as levels where stacking order of el3 is actually 3.8 which is lower than 5.

    If you want to check stacking contexts of parent elements, you can use this:

    var el = document.getElementById("#yourElement"); // or use $0 in chrome;
    do {
        var styles = window.getComputedStyle(el);
        console.log(styles.zIndex, el);
    } while(el.parentElement && (el = el.parentElement));
    

    There is a great article about stacking contexts on MDN

提交回复
热议问题