Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery how do I get a div element to center vertically and horizontally on page load?

Here is the fiddle.

HTML:

<div id="greeter" class="welcomer">
    <h1>This should be centered</h1>
</div>

jquery:

$(document).ready(function(){

$(window).resize(function(){

    $('.welcomer').css({
        position:'absolute',
        left: ($(window).width() - $('.welcomer').outerWidth())/2,
        top: ($(window).height() - $('.welcomer').outerHeight())/2
    });

});

// To initially run the function:
$(window).resize();

});​   

There seems to be a bug in how this works. Some times it will center and other times it will only center vertically or horizontally. I am new to javascript and jquery, is there something that I'm doing wrong?

like image 697
JaeGeeTee Avatar asked Nov 20 '25 22:11

JaeGeeTee


1 Answers

Ok, lookie here: http://jsfiddle.net/zQ97A/13/

Basically you need to have width on your container and you also need the following code:

"top": ((($(window).height() - $('.welcomer').outerHeight()) / 2) + $(window).scrollTop() + "px"),
"left": ((($(window).width() - $('.welcomer').outerWidth()) / 2) + $(window).scrollLeft() + "px")
like image 58
hyankov Avatar answered Nov 22 '25 16:11

hyankov