0

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

$('html,body').animate({
    scrollTop: $("#"+div).offset().top},
'slow');

thanks

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

Community
  • 1
  • 1
Alaa M. Jaddou
  • 1,180
  • 1
  • 11
  • 30

2 Answers2

5

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!

2

Here is an example centering div2: https://jsfiddle.net/2mb44kfa/

HTML:

<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>

CSS:

#div1,
#div3 {
    height: 1000px;
}

#div2 {
    height: 100px;
    background: red;
}

JS:

var winHeight = $(window).height();
var divHeight = $("#div2").height();
var height = (divHeight - winHeight) / 2
$('html, body').animate(
    {
        scrollTop: ($("#div2").offset().top + height) + 'px'
    }, 'slow'
);
AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43