Categories
JavaScript Answers

How to scroll to the middle of the element with JavaScript scrollIntoView()?

Spread the love

Sometimes, we want to scroll to the middle of the element with JavaScript scrollIntoView().

In this article, we’ll look at how to scroll to the middle of the element with JavaScript scrollIntoView().

How to scroll to the middle of the element with JavaScript scrollIntoView()?

To scroll to the middle of the element with JavaScript scrollIntoView(), we can set the block and inline properties to 'center'.

For instance, we write

document.getElementById("myID").scrollIntoView({
  behavior: "auto",
  block: "center",
  inline: "center",
});

to select the element we want to scroll to with getElementById.

Then we call scrollIntoView with an object with block and inline properties set to 'center' to scroll to the middle of the element we selected.

Conclusion

To scroll to the middle of the element with JavaScript scrollIntoView(), we can set the block and inline properties to 'center'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *