How to get scrollbar width with javascript (in latest chrome)

Viewed 593

I want to find the scrollbar width with JavaScript to use it in CSS. I've tried this:

document.documentElement.style.setProperty('--scrollbar-width', (document.offsetWidth - document.clientWidth) + "px");

But I've had no luck. I'm running chrome 86.

1 Answers

Well you can style it but its not widely supported on older versions of most browsers just take that in consideration, to get the width you can do one of many things, on top of my head you could use

const scrollWidth = document.querySelect('.your-element-class').offsetWidth - document.querySelector('.your-element-class').clientWidth;

since offsetWidth is including scrollbarwidth and clientWidth is excluding

Related