willmcpo / body-scroll-lock

Body scroll locking that just works with everything 😏
MIT License
4.04k stars 337 forks source link

Scroll bar gap is ~1px off for certain zoom ranges #145

Open jooleeanh opened 4 years ago

jooleeanh commented 4 years ago

Tested browsers:

How to reproduce:

When using the reserveScrollBarGap: true option and having the zoom set between 67 and 110%, the scrollBarGap will be incorrectly calculated, having a 1px offset. The zoom range changes depending on the viewport width (with dev window open to the side, 110% works fine, but when closed, there's the 1px offset).

Possible solution:

The scrollBarGap is currently calculated with: const scrollBarGap = window.innerWidth - document.documentElement.clientWidth; When I used a custom solution for the body scroll lock, I would calculate it by measuring the body width before and after applying the overflow:none property.

I tested the following:

const div = document.createElement('div');
div.style = "width: 20px; height: 1px; overflow: scroll; visibility: hidden;";
//hiddenBodyDiv.appendChild(div);
document.body.appendChild(div);
console.log(getComputedStyle(div).width);
div.style.overflow = "hidden";
console.log(getComputedStyle(div).width);

Which logs the following (Chrome): Zoom 110%: 6.36364px, 20px Zoom 100%: 5px, 20px Zoom 90%: 3.33333px, 20px Zoom 80%: 1.25px, 20px

From what I can see, it's the decimals that make the difference, since the current method is always at the closest rounded integer.