position:sticky is not working

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>


The 2 most common culprits why position: sticky; might not work are:

  1. You haven't defined top: 0;, bottom: 0;, left: 0 or something similar
  2. One of the parents of your sticky element has overflow (x or y) set to hidden, scroll or auto.

For me it was the first one.