Good old Stackoverflow. Wasn’t sure how to post this without looking like I’m trying to get search engine hits. However, wanted to pass this one on anyhow.
How to center a div using jQuery.
Have used it. Works brilliantly. Although the:
this.css("position","absolute");
May be overkill since any “pop up” div I create already has that in the style where personally I think it should be.
How does it work? Well break down the “top” part:
this.css("top", ( jQuery(window).height() - this.height() ) / 2+jQuery(window).scrollTop() + "px");
To
jQuery(window).height() - this.height() ) / 2
But why not just divide the height by 2? Well say the height of the window is 800 and your item is 600 high. If you just placed the item at 800 / 2, the bottom of the item would end up 1000. (800/2 = 400… 600 tall item + 400 starting point = 1000). So subtracting the item’s height from the window height and THEN dividing by two ensures that that item, provided it is no taller than the window, will end up within the 800 tall window.
+ jQuery(window).scrollTop()
Now what if the user has scrolled the widow down? Well adjust for that. using the scrollTop(), the item can be started at the correct point adjusted with the scroll. Nice huh?