๐ŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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, if you are interested to find out more about CSS layout and other frontend tips you can sign up for my newsletter. You can check out here and here some examples of the js-craft newsletter.

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;
}

๐Ÿ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

๐Ÿ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *