Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I keep position: relative content from overlapping my position: sticky header?

I have a sticky top navbar that I want to stay visible and above all other content when scrolling. I have content on the page that I have set to position: relative so that I can position other elements around it. When I do this, the relative content ignores the navbar when scrolling and overlaps it. Is there any way for my to have my page content positioned relative and still have it observe the sticky navbar?

I've tried giving the relative content a top margin equal to the height of the navbar.

.nav-bar {
  position: sticky;
  top: 0px;
  font-family: Arial, Helvetica, sans-serif;
  border-bottom: solid rgb(179, 173, 173) 1px;
  background-color: rgb(255, 255, 255);
}

.nav-bar #title {
  margin: 0;
  font-size: 2em;
  padding-left: 2%;
}

.test-class #test-content {
  width: 500px;
  height: 500px;
  background-color: rgb(70, 67, 67);
  position: absolute;
}
<div class="nav-bar">
  <p id="title">Title</p>
</div>
<div class="test-class">
  <p id="test-content"></p>
</div>

Expected: sticky header stays above all other content.

Actual: Content overlaps header when its position is set to relative.

like image 728
BCD Avatar asked Sep 11 '19 16:09

BCD


People also ask

Why position sticky does not work?

Troubleshooting position sticky Position sticky will most probably not work if overflow is set to hidden, scroll, or auto on any of the parents of the element. Position sticky may not work correctly if any parent element has a set height. Many browsers still do not support sticky positioning.

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

How to Make position: sticky Work With the overflow Property? By specifying a height on the overflowing container, you should be able to make position: sticky work whilst having the container element have the overflow property set.

What is the difference between sticky and fixed position in CSS?

A sticky element toggles between relative and fixed , depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).


1 Answers

If you want your navbar stay always visible just give it a z-index bigger than your content

.nav-bar{
    position:sticky;
    top:0px;
    font-family: Arial, Helvetica, sans-serif;
    border-bottom:solid rgb(179, 173, 173) 1px;
    background-color: rgb(255, 255, 255);
    z-index: 1
}
like image 59
Davide Castellini Avatar answered Sep 22 '22 07:09

Davide Castellini