Avoid fixed page element "shift" when removing scrollbars on body?

Viewed 29

I'm trying to solve what could be an annoying problem, and I'm sure there is a solution I can't find. I've read a lot of articles like Prevent Page Scrolling When a Modal is Open but none of them speak about fixed element "shift".

What is a fixed element shift? See my pen: click on the hamburger icon and you'll see that the red button itself will "shift" to the right.

Fixed elements layout shift

When the full screen menu opens, I alter the body style via JavaScript, setting overflow and padding-right:

  • āœ… Avoid body content "shift" (blud content): this is solved setting body padding-right equal to the current scrollbar width.
  • Avoid fixed elements "shift" (red button): i cannot avoid this.
const openMenu = e => {
  e.preventDefault();

  // ...
  
  // Change body style
  Object.assign(document.body.style, {
    'overflow': 'hidden',
    'padding-right': `${window.innerWidth - document.documentElement.clientWidth}px`,
  });
};

const closeMenu = e => {
  e.preventDefault();
  
  // ...
  
  // Remove body style
  document.body.removeAttribute('style');
};

EDIT: happens in Chrome 105, Edge 105 on Windows. Doesn't happen in Firefox 104.

0 Answers
Related