clientWidth
from offsetWidth
clientWidth
property indicates the width without scrollbar. The offsetWidth
, on the other hand, includes the scrollbar if there is.const scrollbarWidth = document.body.offsetWidth - document.body.clientWidth;
div
elements, one of them is the child of the other. Then calculate the difference between their widths.const calculateScrollbarWidth = function () {// Create the parent elementconst outer = document.createElement('div');outer.style.visibility = 'hidden';outer.style.overflow = 'scroll';// Append it to `body`document.body.appendChild(outer);// Create the child elementconst inner = document.createElement('div');outer.appendChild(inner);// Calculate the difference between their widthsconst scrollbarWidth = outer.offsetWidth - inner.offsetWidth;// Remove the parent elementdocument.body.removeChild(outer);return scrollbarWidth;};