开发者

Centering a div on a page using jQuery when the page is longer than the window

开发者 https://www.devze.com 2023-02-01 03:13 出处:网络
I need to take this question one step further. The div I have is centered vertically using the following code:

I need to take this question one step further.

The div I have is centered vertically using the following code:

var boxheight = $('#notifications').height();
var windowheight = $(window).height();
var boxheight = $('#notifications').height();
var pagecenterH = ((windowheight-boxheight)/2);
$('#notifications').animate({'top': pagecenterH});

That works great if the page is only as tall as the window, but if the page is much longer and the user is halfway down the page when they click to open the #notifications code above, the div appears centered from th开发者_运维技巧e top of the screen, so they may miss the box altogether.

How can I get the code to recognize where on the page the user is so that the div will appear vertically centered no matter how far down they scroll?

Thanks in advance!


You're going to want to use document instead of window. See here:

http://jsfiddle.net/GftBg/1/

In your code, replace $(window).height() with $(document).height().

If you want a <div> to always be centered in the screen regardless of where the user scrolls after the <div> is loaded in, you should use $(window).height() and set the <div>'s position to fixed. You can see this in action here:

http://jsfiddle.net/GftBg/2/


You can use position:fixed to place the element relative to the window instead of relative to the page. That way it will show up centered, and remain centered even if the user scrolls.


Try below code, in this we are first centering the div in window to to bring it in user view we add scroll top and scroll left to it -

    $('#notifications').css("position","absolute");
    $('#notifications').css("top", ( $(window).height() - $('#notifications').height() ) / 2+$(window).scrollTop() + "px");
    $('#notifications').css("left", ( $(window).width() - $('#notifications').width() ) / 2+$(window).scrollLeft() + "px");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号