- Docs
Scroll Lock
What @samline/scroll-lock does, how nested locks, the scrollbar gap and the iOS Safari workaround fit together, and where to start.
@samline/scroll-lock stops the page from scrolling while a modal, drawer or menu is open, and gives it back exactly as it was. Mark the element with data-scroll-lock, or call lockScroll() from your code.
<dialog id="terms" data-scroll-lock>…</dialog>
How a lock works
- The first lock marks
<html>withdata-scroll-lock-state="locked"and measures the scrollbar. - On desktop and Android it sets
overflow: hiddenon<html>and adds the scrollbar width to<body>’s right padding, so nothing shifts. The width is also published as--scroll-lock-gap. - On iPhone and iPad, where
overflow: hiddendoes not stop the page, it blocks page touches instead, offsets the body by the scroll position and keeps focused inputs above the keyboard. - Every further lock only counts. The page unlocks after the last release, in any order, and the scroll position is where it was.
Pieces
| Job | How |
|---|---|
| Lock while a dialog or menu is open | data-scroll-lock with autoScrollLock(), or the CDN script |
| Lock from code | const unlock = lockScroll() |
| One lock per component | createScrollLock() → lock, unlock, toggle |
| Watch elements you pass | scrollLock(target, options) |
| Keep fixed elements still | padding-right: var(--scroll-lock-gap, 0px) |
| Pin the body | positionFixed: 'safari' or 'always' |
| Release everything | resetScrollLock() |
Choose your next step
Installation
Package managers, the CDN and the first lock.
ExamplesLive previews with the complete, copyable source of each one.
API referenceSignatures and behavior of every function and window.ScrollLock.
Options, attributes, the state attribute and --scroll-lock-gap.
Nesting, the scrollbar gap, iOS Safari and positionFixed.
What a lock does and does not do for focus, inert content and motion.
Framework integrationsReact, Vue, Svelte, Astro and client-side routers.