I have run into a bit of a problem here with displaying two sticky elements that don't share a parent. I am trying to get .the-second-sticky
(some kind of table header) to be on top of the .dropdown-parent
's background, which means it should have a higher z-index. At the same time, the child of .dropdown-parent
is an expandable menu, and I would like for the menu to be over .the-second-sticky
. But I couldn't find a way to do it, as there is no way to make a child have a higher z-index than its parent. Can anyone help me out with this?
In the snippet below, you can start scrolling to get the sticky elements to line up at the top, then click the expand button to expand the dropdown menu.
const btn = document.querySelector('button')
let isExpanded = false
btn.onclick = () => {
document.querySelector('.dropdown').style.height = isExpanded ? '' : '500px'
isExpanded = !isExpanded
}
body {
height: 2000px;
}
.dropdown-parent {
margin-top: 100px;
width: 100vw;
height: 50px;
position: sticky;
top: 0;
background-color: red;
}
.dropdown {
width: 500px;
height: 20px;
background-color: green;
z-index: 9999;
}
.the-second-sticky {
width: 500px;
position: sticky;
top: 30px;
background-color: yellow;
}
button {
position: fixed;
right: 10px;
top: 10px;
}
<div class='dropdown-parent'>
<div class='dropdown'>I should be on the very top</div>
</div>
<div class='the-second-sticky'>I should be on top of the red, but under the green when expanded</div>
<button>Toggle</button>