Alex Rivera | Logout

Centering a div vertically & horizontally using jQuery

Asked 2012-12-16T17:10:14.393
37

I am using this script to center my div horizontally and vertically.

When the page loads the div gets centered vertically, not horizontally until I resize the browser.

What am I doing wrong?

$(document).ready(function (){
    $(window).resize(function (){
        $('.className').css({
            position:'absolute',
            left: ($(window).width() - $('.className').outerWidth())/2,
            top: ($(window).height() - $('.className').outerHeight())/2
        });
    });
    $(window).resize();
});
Edit
Report

1 Answer

3

Related to your code snippet, you need to set the position first:

$(window).resize(function (){
    var $el = $('.className');
    $el.css('position', 'absolute').css({
        left: ($(window).width() - $el.width()) / 2,
        top: ($(window).height() - $el.height()) / 2
    });
});

Maybe you could set the position attribute via a static CSS style.

answered 2012-12-16T17:40:16.203

Your Answer