Reputation: 13672
I am using this method to center a div vertically on my page:
$(window).resize(function() {
$('.container').css({
top : ($(window).height() - $('.container').outerHeight()) / 2
});
});
$(window).resize();
But the code doesn't work initially. I couldn't figure out what was going on until I tried physically resizing the window while the page is loading. As soon as I physically resize the browser window, the div centered immediately. Any way around this? Why is that happening in the first place?
Thanks!
Upvotes: 1
Views: 3189
Reputation: 1143
The way I accomplished similar code is to define a helper function that centers the div (in the jquery onDocumentReady):
$(function () {
function _centerDiv() {
$('.container').css({
top : ($(window).height() - $('.container').outerHeight()) / 2
});
}
_centerDiv();
}
I then hooked into the window's resize event:
$(window).resize(function () {
_centerDiv();
}
When you want to programmatically trigger it (either on-load in the document ready, as above, or to any other event, just call the helper function.
John
Upvotes: 1
Reputation: 5985
You need to run this code on load as well as on resize
$(document).ready(function(){
$('.container').css({
top : ($(window).height() - $('.container').outerHeight()) / 2
});
$(window).resize(function() {
$('.container').css({
top : ($(window).height() - $('.container').outerHeight()) / 2
});
});
});
Upvotes: 3