CSS position Sticky and Z-Index overlay/modal
Asked Answered
N

2

27

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>
Nefen answered 1/11, 2018 at 16:43 Comment(2)
Do you mind adding an example of how it should look?Provincetown
Like this: codepen.io/anon/pen/NOQVbG (position: sticky replaced with relative)Nefen
B
22

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.

Blurb answered 1/11, 2018 at 18:46 Comment(3)
I had this problem in react. There it can be solved by using a portalJeneejenei
I added z index on my sticky element but still it does not show in frontCaitlyncaitrin
I have the same problem with Blazor. I tried with z-index but it didn't work. Any solution yet?Carbrey
B
1

In my case I had sticky element which should go above other sticky

sticky1:
  z-index: 10000
sticky2:
 z-index: 1
 absolute3:
  z-index: 10001

Above will never work (absolute3 will not appear above sticky1)

The solution:

change sticky2 z-index to z-index at least 10000

Bassorilievo answered 6/2 at 12:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.