Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Top 3 reasons why the CSS position sticky may not work

These days I had to rewrite a few elements on different pages to use a position sticky. Mainly navigations menus needed to be sticky at the top of the screen as the user scrolls down.

While refactoring these components I've seen a few common issues that were preventing the position:sticky to do its job. Let's see them one by one:

  1. Position sticky works only if any of the top, left, bottom, right props is set. It will not work without one of these values.
  2. Check if a parent element has the overflow property set to scroll, hidden, or auto. If the overflow of a parent is set to anything else than the default value (visible) then it may break your sticky element.
  3. And maybe the most tricky: if the direct ancestor of the sticky element has display:flex then be sure to have on the sticky element align-self: flex-start.

By the way, found this article to be quite helpful while debugging the "stickiness" of an element. Cool stuff! I really like the JS script from the article. You can paste in the dev tools to check if the overflow of a parent breaks the sticky position:

let parent = document.querySelector('.sticky').parentElement;
while (parent) {
    const hasOverflow = getComputedStyle(parent).overflow;
    if (hasOverflow !== 'visible') {
            console.log(hasOverflow, parent);
    }
    parent = parent.parentElement;
}
Home Screencasts Best of Newsletter Search X