水平居中 [英] Center div horizontally
问题描述
在此页面上,我想水平居中主要的#container div相对到页面。通常我会通过添加一个CSS规则来实现这一点。
#container {margin:0 auto}
$然而,这个页面的布局(我没有写),使用绝对定位#container和它的大部分子元素,所以这个属性没有效果。
有没有办法,我可以实现这个水平居中,而不重写布局使用静态定位?如果这是实现我的目标的唯一方法,我没有问题。
解决方案与@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屋!