skip to Main Content

I’m facing a problem with the position sticky. I try to do header shrink while scrolling but the header is shaking.

But when I change to position: fixed it’s working fine. what’s the problem with sticky?

I’m updating the height style while scrolling.

I have added the StackBlitz link to reproduce the problem.

JSX

    <>
      <div id="header">Header</div>
    </>
      useEffect(() => {
        function scrollFunction() {
          if (window.scrollY > 50) {
            document.getElementById('header').style.height = '45px';
          } else {
            document.getElementById('header').style.height = '90px';
          }
        }

        window.addEventListener('scroll', scrollFunction);
        return () => {
          window.removeEventListener('scroll', scrollFunction);
        };
      }, []);

CSS

#header {
  background-color: #f1f1f1; 
  padding: 10px 10px;
  color: black;
  text-align: center; 
  font-size: 90px;
  font-weight: bold;
  position: sticky; 
  top: 0;
  width: 100%; 
  transition: 0.2s;
}

stackblitz link

2

Answers


  1. I think, what is happening here is that when the window.scrollY gets past 50 and the height of the header is reduced, the value of window.scrollY also gets reduced (because the scroller moves up) due to that reduced height.

    When the header is in this transition area, both the if and else statements keep executing because of the change in window.scrollY. (the transition: 0.2s; makes it worse) You can confirm this by checking the elements in the dev tools.

    I don’t know any solution for this, but maybe you can ignore it as we need to scroll carefully to the point of the transition to reproduce this, normally it should not happen and no one will notice it. Or you could create another sticky header that will appear after scrolling past the main header.

    Login or Signup to reply.
  2. @Akshay is correct, but there is a solution to this.
    You can add a transition in CSS so it won’t lag. This is how you can add the transition.

    You will need to add this to the nav bar for the transition:

    transition: height 0.4s linear;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search