Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

Today I discovered a tweet by Stuart Langridge that shared a surprising fact about the DOM method scrollIntoView. scrollIntoView allows you to bring elements back into the visible viewport by scrolling the parent container.

MDN defines the method as follows:

The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user.

document.querySelector('.some-elem').scrollIntoView();

So far so clear, but did you know that scrollIntoView accepts an options object to configure three things: behavior, block and inline.

document.querySelector('.some-elem').scrollIntoView({
  behavior: 'smooth', // 'auto' or 'smooth'
  block: 'center',    // 'start', 'center', 'end' or 'nearest'
  inline: 'center'    // 'start', 'center', 'end' or 'nearest'
});

Use the behavior property to scroll an element into the visible area with "smooth scrolling".

block and inline let you define an element's scroll position on the block and inline axis when using scrollIntoView. In a top-to-bottom and left-to-write writing mode, the block dimension is the Y-axis and the inline dimension is the X-axis. If you want to read more about writing modes, I recommend reading this article from Rachel Andrew.

Possible scroll position values for both axes are start, center and end. If you don't want to choose a final scroll position but want to scroll as little as possible nearest is an option, too.

Scroll into view devsheets

This is very cool stuff! I'd love it if people used this feature more often because I prefer elements to be scrolled to the viewport center rather than the top or bottom.

If you want to play around with it, I wrote a quick CodePen and tweeted a short video.

Can you use scrollIntoView with options across all browsers?

MDN Compat Data (source)
Browser support info for `options` parameter
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
616179363614148.061

Yep! 💪

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles