简体   繁体   中英

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?

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")

To my taste it's better to have a class defined en a css, and then set that class to a div into your dom with jquery.

#custom.css
.center {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -(your_div_height/2)px;
  margin-left: -(your_div_weight/2)px;
}

#custom.js
$(#greeter).addClass("center")

I thing this is more faster becouse the css files load before the js files

如果您为.welcomer DIV定义宽度,您的代码将完美运行!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM