Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position a fixed element below another fixed element

I have two fixed elements, one of which can either have display: block or display: none. The other fixed element is always going to be visible. I want the elements to stick to the top of the website, while having them not overlay each other.

The only proposed solution I found is in these questions:

How to position a fixed div under another fixed div?

Fixed element below fixed element without JS

Put your two divs inside another container div and set that one as fixed.

I can't do that however, as both of these elements are on different positions in the code, which I am not able to change.

Here's a code snippet demonstrating my problem:

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>

What I want and things to keep in mind:

  • If both elements are visible, they should be fixed on top of the page, while one is below the other
  • If only the second element is visible, I want the second one to be fixed at the top of the page
  • The first element can change its visibility using inline styles (display:none <-> display:block, even without reloading the website)
  • Javascript/Jquery solutions are fine
like image 595
Maharkus Avatar asked Mar 07 '26 02:03

Maharkus


1 Answers

this could bo done adding a 'top' with the height of the first nav to the second, like i did here.

Note: This is not the complete solution: If you want to show the second nav only you could do this using js by setting the 'top' back to 0.

nav,
.secondmenu {
  position: fixed;
  height: 120px;
  opacity: 1;
  top: 0;
  width: 100%;
  background: lightgrey;
}

.secondmenu {
  height: 50px;
  background: grey;
  opacity: 1;
  z-index: 2;
  top: 120px;
}

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>
like image 118
jsadev.net Avatar answered Mar 08 '26 16:03

jsadev.net



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!