为布局更新提供的上下文
我的页面结构相对简单。该页面由两个div组成,两个div都是绝对定位的。一个在另一个中心。
<div id="protocol_index_body_wrapper">
<div id="protocol_index_body">
</div>
</div>
哪个有相应的CSS:
#protocol_index_body_wrapper {
background: url("/images/stripe.png") repeat scroll 0 0 transparent;
position: absolute;
top: 120px;
left: 0px;
right: 0px;
bottom: 10px;
}
#protocol_index_body {
width: 960px;
margin: 0 auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
预期行为见上图。 IE8,Firefox和Chrome中存在此行为。但是,在IE7中,应该居中的div与左侧齐平。有什么想法吗?
答案 0 :(得分:4)
试试这个:
#protocol_index_body {
width: 50px;
margin: 0 auto 0 -25px;
position: absolute;
top: 0;
left: 50%;
right: 0;
bottom: 0;
background-color: red;
}
或......
#protocol_index_body {
width: 50px;
margin: 0 auto 0 50%;
position: absolute;
top: 0;
left: -25px;
right: 0;
bottom: 0;
background-color: red;
}
答案 1 :(得分:0)
除非你需要父div具有流体宽度(当你设置子div的宽度时会有点傻),为什么不设置父div的宽度并添加margin:0 auto
?
答案 2 :(得分:0)
好的,我玩过它,这在FF,Opera和IE7中都是一样的:
#protocol_index_body_wrapper {
background-color:black;
padding: 0 0 20px 0;
position: absolute;
top: 120px;
left: 0px;
right: 0px;
bottom: 10px;
text-align: center;
width: 100%;
height: 100%;
}
#protocol_index_body {
width: 50px;
margin: 0 auto;
background-color: red;
height: 100%;
}
答案 3 :(得分:0)
autoCenterAlign = function() {
var bodyWidth = $("body").innerWidth();
var protocolWidth = $("#protocol_index_body").innerWidth();
if(protocolWidth < bodyWidth) {
$("#protocol_index_body").css("left",((bodyWidth-protocolWidth)/2)+"px");
}
}
window.onload = autoCenterAlign;
window.onresize = autoCenterAlign;
jQuery(window).load(function () {
autoCenterAlign()
});
答案 4 :(得分:-1)
text-align:center
到包装器,或<div align=center>
(丑陋,我知道,但有效)
或与JS:
document.getElementById("protocol_index_body_wrapper").style.marginRight = (document.body.clientWidth - 50)/2_+"px"
仅适用于IE6 +。