0

Why does translateX using vw leave uneven spacing when there is a scrollbar?

When I translate the ul elements away from each other upon scrolling, the leftover space between the start of the viewport and the first ul is smaller than the space between the end of the viewport and the last ul. This only happen when there is a scrollbar in the page. Here are the snippets:

<nav class='navbar flex-container'>
  <ul class='nav-item__container flex-container'>
        ...
  </ul>
  <ul class='nav-item__container flex-container'>
        ...
  </ul>
</nav>
nav {
  display: flex;
  justify-content: center;
  align-items: center;
}

.nav-container.scrolled nav .nav-item__container:nth-child(1) {
  transform: translateX(calc(-50vw + 100%));
}

.nav-container.scrolled nav .nav-item__container:nth-child(2) {
  transform: translateX(calc(50vw - 100%));
}

I fixed this by getting the width of the scrollbr and adding it to the original translateX of the first ul element.

let scrollbarWidth = window.innerWidth - body.offsetWidth;

window.addEventListener('scroll', function() {
    // nav menu item animatate on scroll
    if (window.scrollY >= 10) {
        navContainer.classList.add('scrolled');
        navItemContainer.style.transform = `translateX(calc(-45vw + 100% + ${scrollbarWidth}px))`;
    } else {
        navContainer.classList.remove('scrolled');
        navItemContainer.removeAttribute('style');
    }
});
Domino
  • 37
  • 8
  • Does this answer your question? [Is it possible to calculate the Viewport Width (vw) without scrollbar?](https://stackoverflow.com/questions/33606565/is-it-possible-to-calculate-the-viewport-width-vw-without-scrollbar) – Fabian S. Oct 18 '21 at 06:41
  • 1
    "vw" calculates the width of screen including scrollbar. – Zain Oct 18 '21 at 07:16

0 Answers0