From 3900765cca993c5550f907ed91cfea3818bd85d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zacharias=20Bj=C3=B6rngren?= Date: Tue, 2 Dec 2025 14:01:13 +0100 Subject: [PATCH] [material-ui] Adjust getScrollbarSize to account for browser zoom level --- .../src/getScrollbarSize/getScrollbarSize.ts | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/packages/mui-utils/src/getScrollbarSize/getScrollbarSize.ts b/packages/mui-utils/src/getScrollbarSize/getScrollbarSize.ts index 2cc378ca44a124..15436bd79db9b8 100644 --- a/packages/mui-utils/src/getScrollbarSize/getScrollbarSize.ts +++ b/packages/mui-utils/src/getScrollbarSize/getScrollbarSize.ts @@ -1,7 +1,24 @@ // A change of the browser zoom change the scrollbar size. -// Credit https://github.com/twbs/bootstrap/blob/488fd8afc535ca3a6ad4dc581f5e89217b6a36ac/js/src/util/scrollbar.js#L14-L18 +// Credit https://github.com/twbs/bootstrap/blob/0907244256d923807c3a4e55f4ea606b9558d0ca/js/modal.js#L214-L221 +// and https://github.com/twbs/bootstrap/blob/0907244256d923807c3a4e55f4ea606b9558d0ca/less/modals.less#L122-L128 export default function getScrollbarSize(win: Window = window): number { - // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes - const documentWidth = win.document.documentElement.clientWidth; - return win.innerWidth - documentWidth; + const scrollDiv = win.document.createElement('div'); + + scrollDiv.style.setProperty('position', 'absolute'); + scrollDiv.style.setProperty('top', '-9999px'); + scrollDiv.style.setProperty('width', '50px'); + scrollDiv.style.setProperty('height', '50px'); + scrollDiv.style.setProperty('overflow', 'scroll'); + // Invert the zoom level to get 100% sized scrollbars for the element + scrollDiv.style.setProperty('zoom', `${1 / win.devicePixelRatio}`); + + win.document.body.append(scrollDiv); + + const unZoomedScrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; + + win.document.body.removeChild(scrollDiv); + + const zoomedScrollbarWidth = unZoomedScrollbarWidth / win.devicePixelRatio; + + return zoomedScrollbarWidth; }