Guide

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

  1. The first lock marks <html> with data-scroll-lock-state="locked" and measures the scrollbar.
  2. On desktop and Android it sets overflow: hidden on <html> and adds the scrollbar width to <body>’s right padding, so nothing shifts. The width is also published as --scroll-lock-gap.
  3. On iPhone and iPad, where overflow: hidden does not stop the page, it blocks page touches instead, offsets the body by the scroll position and keeps focused inputs above the keyboard.
  4. Every further lock only counts. The page unlocks after the last release, in any order, and the scroll position is where it was.

Pieces

JobHow
Lock while a dialog or menu is opendata-scroll-lock with autoScrollLock(), or the CDN script
Lock from codeconst unlock = lockScroll()
One lock per componentcreateScrollLock() → lock, unlock, toggle
Watch elements you passscrollLock(target, options)
Keep fixed elements stillpadding-right: var(--scroll-lock-gap, 0px)
Pin the bodypositionFixed: 'safari' or 'always'
Release everythingresetScrollLock()

Choose your next step