Solution to why CSS ‘position: sticky’ is not working

Last Updated:
    CSS position sticky not working

    This post contain affiliate links to Udemy courses, meaning when you click the links and make a purchase, I receive a small commission. I only recommend courses that I believe support the content, and it helps maintain the site.

    An issue that took far longer than it should have to solve.

    I was using the CSS position: sticky on my header so it moved down as the user scrolled. However when I added the mobile menu which transitioned in from the right, the sticky header broke. Could not understand why!

    Turns out sticky does not play nicely with most overflow values.

    If you are trying to use position: sticky and it is not working, it is because one of the elements wrapping it is using overflow with a value of hidden, auto or scroll.

    How to solve the CSS position sticky issue?

    There is a new (ish) value that can be used with overflow. It is clip.

    As Mozilla puts it in their documentation:

    Similar to hidden, the content is clipped to the element’s padding box. The difference between clip and hidden is that the clip keyword also forbids all scrolling, including programmatic scrolling. The box is not a scroll container, and does not start a new formatting context. If you wish to start a new formatting context, you can use display: flow-root to do so.

    Is Clip supported on all modern browsers.

    At time of writing (23/11/2022) all current versions of modern browsers support this functionality. Take a look at Can I Use if you want to check for yourself.

    Still not working?

    If it is still not working, you may need to double check that a placement position has been set. This can be left, right, bottom, or top as a minimum. This could look like:

    .element {
      position: sticky;
      top: 0;
    }

     

    Hopefully this helped you, and if you have any questions you can reach me at: @robertmars

    Tags:

      Related Posts

      Helpful Bits Straight Into Your Inbox

      Subscribe to the newsletter for insights and helpful pieces on React, Gatsby, Next JS, Headless WordPress, and Jest testing.