使用CSS,我想在div中水平居中两个“盒子”。盒子绝对定位。
这是JSFiddle:http://jsfiddle.net/p4sA3/8/
如果不使用特定宽度,我将如何实现这一目标?
HTML:
<button id="change">Change</button>
<div id="total-wrap">
<div id="hello-wrap" class="bunch">
<div id="box">
<p> Hello, this is text1 </p>
</div>
<div id="box">
<p> Hello, this is text2 </p>
</div>
</div>
<div id="goodbye-wrap" class="bunch">
<div id="box">
<p> Goodbye, this is text1 </p>
</div>
<div id="box">
<p> Goodbye, this is text2 </p>
</div>
</div>
</div>
CSS:
#total-wrap {
border:1px solid #000;
height:500px;
}
#box {
position:relative;
display:inline-block;
width:300px;
height:100px;
background-color:yellow;
margin:10px;
}
.bunch {
position: absolute;
text-align:center;
}
答案 0 :(得分:3)
我会使用left:0;
和right:0
,因为它们绝对定位。
DEMO http://jsfiddle.net/kevinPHPkevin/p4sA3/19/
.bunch {
position: absolute;
text-align:center;
left:0;
right:0;
}
答案 1 :(得分:0)
<强>解决方案:强>
#total-wrap {
border:1px solid #000;
height:500px;
}
#box {
display:inline-block;
width:300px;
height:100px;
background-color:yellow;
margin:10px;
text-align:center;
}
.bunch {
text-align:center;
}
答案 2 :(得分:0)
<div id="wrap">
<div id="left">Box1</div>
<div id="right">Box2</div>
</div>
#wrap {
background: #e7e7e7;
padding: 40px;
text-align: center;
width: auto;
}
#left, #right {
background: yellow;
display: inline-block;
padding: 20px;
}
答案 3 :(得分:0)
这是你想要的吗?
#box {
position:relative;
display:inline-block;
width:100px;
height:100px;
background-color:yellow;
margin:10px;
}
DEMO:http://jsfiddle.net/p4sA3/11/
问题是,只要宽度的总和超过容器,第二个div就会位于第一个div之下
在另一个演示中,我没有使用宽度:http://jsfiddle.net/p4sA3/13/
答案 4 :(得分:0)
如果你想使用jQuery:
keepCentered = function() {
$('#hello-wrap').css({'margin-left':($('#total-wrap').width()-$('#hello-wrap').width())/2});
$('#goodbye-wrap').css({'margin-left':($('#total-wrap').width()-$('#goodbye-wrap').width())/2});
}
$(document).ready(keepCentered);
$(window).bind('resize', keepCentered);