A small unobtrusive script aimed to encourage a CSS-first approach when locking HTML elements scroll. It is entirely written in vanilla JavaScript with no dependencies.
Without scrollbar gap compensation:
With scrollbar gap compensation:
It can be installed via npm:
npm install scroll-padlockimport { setStyle } from "scroll-padlock";
setStyle();The library exports a setStyle function that appends CSS styles targeting the default .scroll-padlock selector. By default, it uses the page's scrolling element and the window object to retrieve values, which are then assigned to CSS variables for use as preferred.
The appended CSS variables can be used to implement the preferred approach to prevent the element scroll or to add the scrollbar gap componsation, see the following basic example:
.scroll-padlock {
overflow: hidden;
padding-right: var(--scrollbar-width, 0px);
}Since each function call updates the CSS variables, a good time to call it is immediately before adding the CSS class that would lock the element scroll.
setStyle();
document.scrollingElement.classList.add('scroll-padlock');The setStyle function accepts an options object which customizes its behavior. Here are the available options:
element: the DOM element that will be used to retrieve the CSS variables values.selector: the CSS selector string that identifies the target element.formatter: a function that allows to customize the the CSS styles to be added.
setStyle({
element: document.querySelector('#custom-scrolling-element'),
selector: '.custom-element-scroll-padlock',
formatter: ({
offsetWidth, // The total layout width of the element in pixels, including scrollbars.
offsetHeight, // The total layout height of the element in pixels, including scrollbars.
clientWidth, // The inner width of the element in pixels, excluding scrollbars.
clientHeight, // The inner height of the element in pixels, excluding scrollbars.
scrollWidth, // The full width of the element's content, including content not visible due to overflow.
scrollHeight, // The full height of the element's content, including content not visible due to overflow.
scrollTop, // The number of pixels that the element's content is scrolled vertically.
scrollLeft, // The number of pixels that the element's content is scrolled horizontally.
}) => `--scrollbar-width: ${offsetWidth - clientWidth}px;`
});Node version 22.16.0 or higher is required in order to execute the tests.
npm testThe locally built library is imported in the end-to-end tests, so a build is required.
npm run build
