eatonphil
eatonphil

Reputation: 13672

jQuery centering div to window vertically resizing issue

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

Answers (3)

sites
sites

Reputation: 21775

Check this JSBin

I added positioning:

 position: 'absolute'

Upvotes: 1

John Kroetch
John Kroetch

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

ntgCleaner
ntgCleaner

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

Related Questions