水平居中 [英] Center div horizontally

查看:115
本文介绍了水平居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  #container {margin:0 auto} 


有没有办法,我可以实现这个水平居中,而不重写布局使用静态定位?如果这是实现我的目标的唯一方法,我没有问题。

解决方案

与@rquinn答案相同但这将调整到任何宽度。检查此演示



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



HTML:

 < div id =container>< / div> 

CSS:

 code> * {margin:0; padding:0; } 
#container {
width:50px;
position:absolute;
height:400px;
display:block;
background:#ccc;
}

Javascript

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

$(document).ready(function(){
setMargins();
$(window).resize b setMargins();
});
});


On this page, I would like to horizontally center the main #container div relative to the page. Normally I would achieve this by adding a CSS rule,

#container { margin: 0 auto }

However, the layout of this page (which I did not write), uses absolute positioning for #container and most of its child elements, so this property has no effect.

Is there any way I can achieve this horizontal centering without rewriting the layout to use static positioning? I've no problem with using JavaScript/JQuery if that's the only way to achieving my objective.

解决方案

Same as @rquinn answer but this will adjust to any width. Check this demo

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

HTML:

<div id="container"></div>

CSS:

* { margin:0;padding:0; }
#container {
    width:50px;
    position:absolute;
    height:400px;
    display:block;
    background: #ccc;
}

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();    
    });
});

这篇关于水平居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆