[英]Alignment with relative and absolute positioning
我怎么能把蓝色盒子放在红色盒子里? 我看到蓝色框的左侧正好位于红色框的中间,但我想将整个蓝色框放在中心,而不是左侧。 盒子的尺寸不是恒定的。 无论盒子尺寸如何,我都想对齐。 在这里玩的例子。 谢谢 !
HTML:
<div id="rel">
<span id="abs">Why I'm not centered ?</span>
</div>
CSS:
#rel {
position: relative;
top: 10px;
left: 20px;
width: 400px;
height: 300px;
border: 1px solid red;
text-align: center;
}
#abs {
position: absolute;
bottom: 15px;
width: 300px;
height: 200px;
border: 1px solid blue;
}
如果您能够将<span>
标记更改为<div>
<div id="rel">
<div id="abs">Why I'm not centered ?</div>
</div>
然后这块CSS应该工作。
#rel {
position: absolute;
top: 10px;
left: 20px;
width: 400px;
height: 300px;
border: 1px solid red;
text-align: center; }
#abs {
width: 300px;
height: 200px;
border: 1px solid blue;
margin: auto;
margin-top: 50px; }
我认为最好为封闭的盒子使用更多的自动化,因为如果更改容器盒的大小,则需要更少的更改。
你可以添加left:50px
到#abs
如果那就是你想要的......
#abs {
position: absolute;
bottom: 15px;
width: 300px;
height: 200px;
border: 1px solid blue;
left:50px;
}
如果你要定义那样的尺寸(200px x 300px和300px x 400px),这里是它如何居中:
#rel {
position: relative;
top: 10px;
left: 20px;
width: 400px;
height: 300px;
border: 1px solid red;
text-align: center;
}
#abs {
position: absolute;
width: 300px;
height: 200px;
border: 1px solid blue;
margin: 49px 0 0 49px;
}
您可以在http://jsfiddle.net/NN68Z/96/查看我的解决方案
我对css做了以下操作
#rel {
position: relative;
top: 10px;
left: 20px;
right: 20px;
width: 400px;
height: 300px;
border: 1px solid red;
text-align: center;
display: table-cell;
vertical-align: middle;
}
#abs {
display: block;
bottom: 15px;
width: 300px;
height: 200px;
border: 1px solid blue;
margin: 0 auto;
}
这应该工作
#abs {
position: absolute;
left: auto;
right: auto;
bottom: 15px;
width: 300px;
height: 200px;
border: 1px solid blue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.