Skip to content Skip to sidebar Skip to footer

Why Sticky Position Does Not Work In Child Div

i have multiple div in html page. when i try to stick menu-bar it does not work and menu-bar is inside the other divs. here is the my code. where am doing mistake? I even tried

Solution 1:

A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.

With that in mind, we know we need our threshold to be met, meaning that top:0 means when #menubar has 0 offset from top of it's containing block.

The containing block in our case is #header and it's height is defined by it's content, therefore the threshold is never met, because there's no overflow/scroll within it.

To see this more clearly we can apply some heights.

#menubar {
  height: 50px;
  width: 100%;
  background-color: red;
  position: sticky;
  /* when there's 10px space left between menubar and header */
  /* make it stick */
  top: 10px;
}

#header {
  border: 5px solid lime;
  height: 1000px;
}

.content {
  border: 5px solid orange;
  height: 1000px;
}
<div id="container">
  <div id="header">
    <div id="bannerbox">
      <img src="images/banner.png" height="100%" width="100%" />
    </div>
    <div id="menubar">
      i'm stuck sticky
    </div>
    <div id="cityinfo">cityinfo</div>
  </div>

  <div id="content" class="content">
    header height is almost done, so the threshold will not be met very soon, this is what's hapening when the header has no overflow/scroll, menubar becomes sticky and goes back to normal almost instantly perhaps it never happens we don't know, it depends
    on how the user agant handles it.
  </div>
  <div id="footer"></div>
</div>

The fix would be to make header all together sticky or change how your html is laid out, i demonstrate either of them, because i don't know which is much more fitting for you, probably changing the markup isn't an option.


Post a Comment for "Why Sticky Position Does Not Work In Child Div"