Reputation: 23
I have a question. I want to align a div on the vertical centre off the browser viewport. I understand how to do this and have written some code myself. But there is one thing that does not work:
// fetch al info I need
var windowHeight = $(window).height();
var pageTop = $(window).scrollTop();
var modalHeight = "98";
// Get the centre of the window
var divTop = (windowHeight - modalHeight) / 2;
// Add the scrollTop so the div will align in the middle of my current browser viewport
var divTop = divTop + pageTop;
var divTop = divTop + "px";
$('#modal_placeholder').css('top',divTop);
Now, the problem is that it will not get the correct scrollTop value ... it always says it's 0, like you are currently at the top of the page.
Can you help me out??
Upvotes: 1
Views: 237
Reputation: 2075
If you want to do this is js-way, you can do such like that:
var d = $(your_div),
div_height = d.height();
d.css({
position: 'absolute',
top: '50%',
margin: '-' + (div_height / 2) + 'px 0 0 0'
})
Upvotes: 1
Reputation: 6127
$(window).scrollTop()
returns how far down the page you have scrolled. Try typing this into your address bar as you're in different positions on the page (any page.)
javascript:alert($(window).scrollTop());
Edit: It seems you already know this. The problem is that the variable is not being updated. When the page loads, $(window).scrollTop()
has a value of 0. To update the value, try binding an event to updating that value.
Upvotes: 0
Reputation: 185963
You could use a TABLE element: http://vidasp.net/CSS_Centering-horizontally-and-vertically.html
Upvotes: 0