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