I have this HTML code:
<div class="header"> <div class="desc">Description</div> <div class="logo"><img src=""/></div> <div class="navbar"></div></div>
.header has a height of 150px. .navbar has a height of 20px. When the user scrolls, I want .navbar to stick at the top. So I went to the CSS and set position:sticky and top:0. But this didn't work. I initially thought that firefox is not supporting position:sticky, but that's not the case because I was able to see a working demo of it. I googled about it but found nothing helpful. Anyone knows why this is not working?
If the parent element has no height set then the sticky element won't have any area to stick to when scrolling. This happens because the sticky element is meant to stick/scroll within the height of a container.
If you've ever tried sticky positioning, then you have probably wondered why CSS position: sticky is not working for your web design. It's because an ancestor element has one of the following values for the overflow property: hidden, scroll, or auto.
To see the effect of sticky positioning, select the position: sticky option and scroll this container. The element will scroll along with its container, until it is at the top of the container (or reaches the offset specified in top ), and will then stop scrolling, so it stays visible.
It is available on Chrome (yay), Firefox and Safari. Here are more details about position:sticky : Specification.
For anyone else that comes across this, position sticky was not working for me due to the body
element having overflow-x: hidden;
set.
It works fine if you move the navbar outside the header. See below. For the reason, according to MDN:
The element is positioned according to the normal flow of the document, and then offset relative to its flow root and containing block based on the values of top, right, bottom, and left.
For the containing block:
The containing block is the ancestor to which the element is relatively positioned
So, when I do not misunderstand, the navbar is positioned at offset 0 within the header as soon as it is scrolled outside the viewport (which, clearly, means, you can't see it anymore).
.navbar { background: hotpink; width: 100%; height: 50px; position: -webkit-sticky; position: sticky; top: 0; } .header { height: 150px; background: grey; } body { height: 800px; position: relative; }
<div class="header"> <div class="desc">Description</div> <div class="logo"><img src=""/></div> </div> <div class="navbar"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With