Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS position Sticky and Z-Index overlay/modal

i have a problem with the position: sticky and z-index

I want my modal in the sticky-element to be overlayed by the overlay. With position: relative it works: the modal is before the overlay. But when I use Sticky the modal is behind the overlay.

Hope it's understandable what I mean. Here's the example:

.sticky {
    position: sticky; /* <-- dosen't work */
    /* position: relative; /* <-- work */
    top: 0;

    width: 100%;
    height: 200vh;
    background: red;
}

.modal {
    z-index: 1000;

    position: fixed; 
    margin: 0 auto;
    width: 200px;
    height: 200px;
    background: yellow;
    margin: 0 auto;
}

.overlay {
    z-index: 999;
    position: fixed;


    width: 100%;
    height: 100%;
    background: green;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    opacity: 0.75;
}
<div class="overlay"></div>
<div class="sticky">
    <div class="modal">modal</div>
</div>
like image 639
milkman Avatar asked Nov 01 '18 16:11

milkman


People also ask

Does position sticky work with Z index?

Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).

Does Z Index work with position relative?

Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).

How do you make position sticky work with the overflow property?

If you really want position: sticky to work on all modern browsers, then you should consider not using overflow: hidden on the <body> or any wrapper surrounding the main content, but rather put a wrapper around elements that will overflow the viewport. Then, those wrappers should use overflow: hidden.

Can I use Z index without position?

z-index only works on positioned elements. If you try to set a z-index on a non-positioned element, it will do nothing.


1 Answers

When you set position: relative, the .modal element is relative to the body because it has position: fixed. As such, the z-index value of 1000 put it in foreground.

When you use position: sticky, the .sticky element is positionned, with the default z-index value. Therefore, it positions itself in background because .overlay's z-index value of 999. .modal being a child of .sticky, it will never be able to go in front of .overlay.

You must change the structure of your HTML, or simply add a z-index on your .sticky element.

like image 196
Thibaut Dupont Avatar answered Oct 07 '22 11:10

Thibaut Dupont