user2478466
user2478466

Reputation: 33

center div vertically jumping in firefox

I have created a script to keep a div centred on the screen. It works fine in safari but for some reason jumps on window resize. I assume is is doubling the negative 'margin-top'. Anyone have any experience with this. I havent tried in chrome or ie.

// PART B
function cent() {
var $block = $("#block"),
    margintop = parseInt($block.height() / -2);
console.log('called');
$('#block').css("margin-top", margintop);
};

$(document).ready(function(){
cent();
});
$(window).resize(function(){
cent();
});

the site url: www.thebackroads.com.au

Upvotes: 0

Views: 87

Answers (2)

Timmetje
Timmetje

Reputation: 7694

If you log $block.height() You will see the javascript generated margin-top at load differs from the one when resizing because it seems your container actually has a different height.

This is probably due to the first cent() call being done when DOM isn't fully loaded. Or at least the text container hasn't reached it's final height because you show a preloader while image is being loaded. The reason for this is probably your external library. See DOM not fully loaded?

You can see this clearly in firebug your content is hidden when you calculate the height.

enter image description here

Read some solutions here:

jQuery: Get height of hidden element in jQuery

Upvotes: 1

yeyene
yeyene

Reputation: 7380

Or try this script? Calculate with window's height.

function cent() {
    var margintop = ($(window).height() - $('#block').height()) / 2;
    $('#block').css("margin-top", margintop);
};

Upvotes: 0

Related Questions