Skip to content

Instantly share code, notes, and snippets.

@justerror
Forked from itrelease/calc-scrollbar-width.js
Last active March 10, 2019 11:17
Show Gist options
  • Save justerror/64aee6d0e96f424071bffd87edc58574 to your computer and use it in GitHub Desktop.
Save justerror/64aee6d0e96f424071bffd87edc58574 to your computer and use it in GitHub Desktop.
Calculate scrollbar width
/**
* @description Calculates scrollbar width
* @export
* @returns {number} Value in px
*/
export function calcScrollbarWidth(): number {
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.width = '100px';
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
document.body.appendChild(outer);
const widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = 'scroll';
// add innerdiv
const inner = document.createElement('div');
inner.style.width = '100%';
outer.appendChild(inner);
const widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment