Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion About z-index

Tags:

html

css

The article in the following link states that z-index stacking is only applicable to sibling elements: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

But the below snippet shows that divs that have different parents are stacked with regard to the z-index. Overlay stays over the text and below the textbox even though both the text and textbox belong to the same parent but not the overlay. How is that possible according to the article?

.overlay {
    background-color: rgba(0, 0, 0, 0.5);
    display: block;
    height: 100%;
    left: 0;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 2;
}
<div class="overlay" style="display: block;"></div>

<div>
    <div>
    Some text that will remain under the overlay.
    </div>
    <div style="width:1000px;">
        <div style="width:50%;position:relative;z-index:2;">
            <div>
                <input style="width:80%;">
            </div>

        </div>
    </div>

</div>
like image 484
John L. Avatar asked Nov 19 '22 09:11

John L.


1 Answers

The problem is your z-index comparison starts from the first relative or absolute positioned DOM element. So basically css z-index ignores all elements that have static position.

 <div class="overlay" style="display: block;"></div>

<div style="position:relative;z-index:3;">
    <div>
    Some text that will remain under the overlay.
    </div>
    <div style="width:1000px;">
        <div style="width:50%;">
            <div>
                <input style="width:80%;">
            </div>

        </div>
    </div>

</div>

I think this should work for you

like image 191
Leonid Lazaryev Avatar answered Jan 03 '23 16:01

Leonid Lazaryev