Why is my position:sticky not working?

When you place a position:sticky element inside another element things can get tricky you may need to set the display property of your parent elements to something besides block.

try adding the following:

.center, header{
  display:initial;
}

You can probably set it to inline or inline-block as well depending on your needs.

Here is your snippet with that added along with a couple of other things just for display purposes:

body{
  height:200vh;
}

.center, header{
  display:initial;
}

.dropmenu {
  display: block;
  height: 65px;
  width: 100%;
  background: url("images/menuicon.png") no-repeat 98% center;
  background-color: #404040;
  cursor: pointer;
}

nav ul {
  padding: 0;
  overflow: hidden;
  background: #505050;
  display: none;
}

nav ul li {
  display: block;
  float: none;
  text-align: left;
  width: 100%;
  margin: 0;
}

nav ul li a {
  color: white;
  padding: 10px;
  border-bottom: 1px solid #404040;
  display: block;
  margin: 0;
}

div.sticky {
  position: sticky;
  top: 0;
}
<div style="height:100px; background:green;"></div>
    
    <div class="center">
        <header>
            <img class="headerImage" src="images/header.png"/>
            <hr class="menu">
            <div class="sticky">
                <a class="dropmenu"></a>
                <nav class="desktop">
                    <ul>
                        <li><a href="index.php">Sertet</a></li>
                        <li><a href="index.php">Rtretrti</a></li>
                        <li><a href="photos.php">ertettterli</a></li>
                        <li><a href="index.php">retemi</a></li>
                        <li><a href="index.php">Kerterti</a></li>
                    </ul>
                </nav>
            </div>
            </header>
        <hr class="menu">
   <p>content goes here</p>
</div>


Usually, it's because of some parent's "overflow" property.

If any parent/ancestor of the sticky element has any of the following overflow properties set, position: sticky won't work:

  • overflow: hidden
  • overflow: scroll
  • overflow: auto

Here's what helped me. Simply copy/paste the following snippet into your browser's console. This will help you to identify all parent elements with overflow property set to something other than visible:

    // Change to your STICKY element
    let parent = document.querySelector('.sticky').parentElement;
    
    while (parent) {
        const hasOverflow = getComputedStyle(parent).overflow;
        if(hasOverflow !== 'visible') {
            console.log(hasOverflow, parent);
        }
        parent = parent.parentElement;
    }

Then it's mostly the issue of setting the right overflow property to the right element.


For me, I found that overflow: hidden; on a parent container was what was breaking the child's position: sticky;. If overflow on the parent is visible, the sticky starts working.

Tags:

Html

Css