Centering an Element Within the Viewport - J Query

Problem
You want to scroll the window to center an element within the viewport.

Solution

Get the viewport’s dimensions; determine the width, height, and offset of the element; and use a little math to center the element in the viewport:

In the final lines, we add the top offset of the element to half the element’s height in order to determine the vertical center of the element. Then we subtract half the viewport’s height to determine the position to which we want the window to scroll. Finally, we do an analogous calculation to center the viewport horizontally.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics