Scrolling an element into view
scrollIntoView({ block: "nearest" })
Chrome1
Edge79
Firefox1
Safari3
Features it needs
- scrollIntoView()Widely available
These packages exist for one behaviour: scroll only if the element is not already visible, and scroll as little as possible when it is not. That is what block: "nearest" does, in every engine. The default is block: "start", which always scrolls and is why the native method got a reputation for being too blunt, so the option is the whole difference.
When this applies
Bringing an element into view, typically a highlighted option or a focused row.
The native approach
// Scrolls only as far as it has to, and not at all if the
// option is already visible. Ideal for keyboard navigation.
option.scrollIntoView({
block: "nearest",
inline: "nearest",
behavior: "smooth",
});When the dependency is still right
An answer that always says "the platform covers it" is worse than no answer. These are the cases where this one does not hold.
- You need the scroll offset computed without applying it. That is what compute-scroll-into-view is for on its own, and a virtualised list that batches its own scrolling genuinely needs the number rather than the movement.
- You need a specific duration or easing. behavior: "smooth" exposes neither, and the browser picks both.
- You must scroll several containers to a coordinated position. The native method walks its own ancestors on its own terms, so a scroll that has to stay in step across panes needs the offsets.
- Your support target reaches below Chrome 61, Firefox 36 or Safari 14. The method is far older than that, so scrollIntoView() existing is not proof the options object is read.
Signs it was hand-rolled
No package is involved in any of these, so nothing would match in a package.json. If the code looks like one of them, this rule applies anyway, and the conditions above still decide.
- getBoundingClientRect on an element and its scroll container, compared to decide whether to set scrollTop
- a scrollTop assignment computed from offsetTop minus the container's height, to centre a highlighted item