简体   繁体   中英

Vertically center layer within the user's viewable area on a long page

I'm trying to vertically center a div in the viewable area on a very long page. The true vertical center of the page is well above the user's viewable area in this case.

I've added the scrollTop() length of the link the users clicks on to the formula which helps, but still places the div above the center of the viewable area.

Code excerpt:

$('.' + layer).css({
    display:'block',
    left:( $(window).width() - $('.' + layer).width() )/2,
    top:( $(this).scrollTop() + $(window).height() - $('.' + layer).height() )/2 -20,
    position:'absolute'
});

Maybe you need CSS solution?

If your DIV's height = H, css will be:

div{ position:fixed; left:0; top:50%; margin-top:(-0.5 * H) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM