Alaa M. Jaddou Alaa M. Jaddou - 1 year ago 92
Javascript Question

scroll page to div

i Need to scroll to div but i don't need the div to be on top of page after scrolling

i need it to be in of page how do i do that to be in
center of the page.

i see many question that make the scrolling right but to top of page i need it to scroll but make the div in center of the page.

i've tried this but this scroll it to top of the page

scrollTop: $("#"+div).offset().top},


How to scroll to specific item using jQuery? is scroll to div but make it at top of page not at center

Answer Source

In order for the div to be centered in the window after scrolling you would need to:

  1. Query the browser's window height (this is doable)
  2. Query the div's height (this is doable, though you need to be careful: height is not always accurately calculated)
  3. Subtract Line 2 from Line 1, then divide by 2
  4. Add the result from Line 3 to your top value

Note: When your div is taller than the browser window, it will still be centered, but the top of the div will be off the screen!