中心div水平

Dón*_*nal 7 css jquery positioning css-position

这个页面上,我想将主#container div相对于页面水平居中.通常我会通过添加CSS规则来实现这一点,

#container { margin: 0 auto }
Run Code Online (Sandbox Code Playgroud)

但是,此页面的布局(我没有写),使用#container及其大多数子元素的绝对定位,因此此属性无效.

有没有什么方法可以实现这种水平居中而不需要重写布局来使用静态定位?如果这是实现我的目标的唯一方法,我使用JavaScript/JQuery没问题.

Sta*_*arx 6

与@rquinn答案相同,但这将调整为任何宽度.查看此演示

http://jsfiddle.net/Starx/V7xrF/1/

HTML:

<div id="container"></div>
Run Code Online (Sandbox Code Playgroud)

CSS:

* { margin:0;padding:0; }
#container {
    width:50px;
    position:absolute;
    height:400px;
    display:block;
    background: #ccc;
}
Run Code Online (Sandbox Code Playgroud)

使用Javascript

function setMargins() {
    width = $(window).width();
    containerWidth = $("#container").width();  
    leftMargin = (width-containerWidth)/2;    
    $("#container").css("marginLeft", leftMargin);    
}

$(document).ready(function() {
    setMargins();
    $(window).resize(function() {
        setMargins();    
    });
});
Run Code Online (Sandbox Code Playgroud)