简体   繁体   English

使用jQuery水平和垂直居中填充全角DIV

[英]Center padded, full-width DIV horizontally and vertically using jQuery

The following code works wonders to center my div as long as there's no padding or 100% width in the css: 只要CSS中没有填充或100%的宽度,以下代码就能使div居中:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}

$(element).center();

Unfortunately, this screws up the padding of my (width: 100%) div in the latests versions of Safari, Firefox, and Chrome (probably all browsers too). 不幸的是,这会破坏Safari,Firefox和Chrome(可能也是所有浏览器)的最新版本中我(宽度:100%)div的填充。 The padding on the left is gone, and the padding on the right still exists, but it's off the page, creating a scrollbar. 左侧的填充消失了,右侧的填充仍然存在,但是不在页面上,从而创建了滚动条。 Any suggestions? 有什么建议么?

Live demo: http://www.pillerdesigns.com/ 现场演示: http//www.pillerdesigns.com/

When I want to center something I normally do this: 当我想居中放置东西时,通常这样做:

jQuery.fn.center = function () {

    this.css({
        position: 'absolute',
        top: 50+'%',
        left: 50+'%',
        marginTop: -(this.outerHeight()/2),
        marginLeft: -(this.outerWidth()/2)
    });

    return this;
}

Anyway, do you have a reset.css? 无论如何,您是否有reset.css? Since your problems are browser specific. 由于您的问题是特定于浏览器的。

$(element).center();

EDIT : 编辑

Add box-sizing: border-box; 添加box-sizing: border-box; to your #content div css. 到您的#content div CSS。

Problem is you're using padding on a 100% width element. 问题是您在100%宽度的元素上使用填充。 box-sizing method will work in all browsers but not IE7 and lower. box-sizing方法适用于所有浏览器,但不适用于IE7及更低版本。

-- OR -- - 要么 -

Wrap your #content div inside another div, make that one 100% and add the padding to the inner div. 将您的#content div包裹在另一个div中,使它成为100%,然后将填充添加到内部div中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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