CSS: How to get browser scrollbar width? (for :hover {overflow: auto} nice margins)
All scrollbar can be different according to browser and OS so you must use javascript.
I found a cool snippet here : http://davidwalsh.name/detect-scrollbar-width
And that an exemple : http://jsfiddle.net/a1m6an3u/
The js code create a div .scrollbar-measure
, look the size of the scrollbar and return it.
It look like this :
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);
// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.warn(scrollbarWidth); // Mac: 15
// Delete the DIV
document.body.removeChild(scrollDiv);
So I quickly added some jquery code but I think you can do it in only JS.
Whilst tomtomtom's answer works fantastically, it requires an external CSS snippet that seems somewhat unnecessary, and Yurii's answer requires jQuery, which again seems sorta overkill for this. A slightly more up-to-date and self-contained answer (which can also be used in a JavaScript module setup) is:
class TempScrollBox {
constructor() {
this.scrollBarWidth = 0;
this.measureScrollbarWidth();
}
measureScrollbarWidth() {
// Add temporary box to wrapper
let scrollbox = document.createElement('div');
// Make box scrollable
scrollbox.style.overflow = 'scroll';
// Append box to document
document.body.appendChild(scrollbox);
// Measure inner width of box
this.scrollBarWidth = scrollbox.offsetWidth - scrollbox.clientWidth;
// Remove box
document.body.removeChild(scrollbox);
}
get width() {
return this.scrollBarWidth;
}
}
This class can then be used like so:
let scrollbox = new TempScrollBox();
console.log(scrollbox.width) //-> 17 (Windows, Chrome)
Fiddle: https://jsfiddle.net/nu9oy1bc/
innerWidth returns the width of the browser viewport including the scrollbar.
The read-only Window property innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present.
clientWidth returns the width of viewport, excluding the scrollbar, when used on a root element like document.
When clientWidth is used on the root element (the element), (or on if the document is in quirks mode), the viewport's width (excluding any scrollbar) is returned.
let scrollbarWidth = (window.innerWidth - document.body.clientWidth) + 'px';
Subtract the two values and voila, you get the width of the scrollbar.
This example would usually return: 15px