Philip Feldmann Philip Feldmann - 1 month ago 4
CSS Question

jQuery calculating height wrong after refresh

i'm using jQuery to vertically center different elements on a page. I wont be able to use the table-cell css-statement, because it's not supported in lower versions of IE, so i'm using jQuery to calculte half of the height and then set it in the middle via negative margin.

This works fine if i just use the adressbar to refresh the page, but if i'm using the reload-button it will calculate the wrong height and set it way too low.
For example, the height of the broken element is 863px but jQuery sets margin-top: -228.5px;

Thanks in advance.

function verticalCenter(object) {
objectHeight = $(object).height() / -2;
$(object).css({'position':'relative','top':'50%','marginTop':objectHeight});
}

$( document ).ready(function() {
verticalCenter("#promo-heading");
verticalCenter("#center1");
verticalCenter("#center2");
});

Answer

If there is any image content on document.ready is not downloaded, and height will be changed after that. Try to use:

$(window).load(function(){
    ...
});