I have a dilemma with two fixed elements on my website. One of them can toggle between display: block
and display: none
, while the other is always visible. I want both elements to stay at the top of the webpage without overlapping each other.
I've come across some related questions:
How to position a fixed div under another fixed div?
Fixed element below fixed element without JS
The suggestion is to place both divs inside a container div and set it as fixed.
Unfortunately, I am unable to follow this advice since the two elements are positioned differently in the code.
Below is a code snippet illustrating my issue:
nav,
.secondmenu {
position: fixed;
height: 120px;
opacity: 1;
top: 0;
width: 100%;
background: lightgrey;
}
.secondmenu {
height: 50px;
background: grey;
opacity: 1;
z-index: 2;
}
body {
height: 1000px;
}
<div class="secondmenu">Might be there or not and overlays the other navigation</div>
<div>Some other stuff separating the two from each other with relative position</div>
<nav></nav>
My requirements and considerations:
- If both elements are visible, they should remain fixed at the top of the page, with one below the other
- If only the second element is visible, it should be fixed at the top of the page
- The visibility of the first element can change dynamically using inline styles (
display:none
<->display:block
, without reloading the website) - I am open to solutions involving JavaScript or jQuery