相对和绝对定位对齐
我怎样才能将蓝色盒子放在红色盒子的中心? 我看到蓝色框的左侧正好位于红色框的中间,但我想将整个蓝色框居中,而不是其左侧。盒子的尺寸不是恒定的。我想对齐,无论盒子尺寸如何。 此处的示例。谢谢 !
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;
}
How could I center the blue box inside the red one ?
I see that the left side of the blue box is exactly in the middle of the red box, but I would like to center the whole blue box, not its left side. The dimensions of the boxes are not constant. I want to align regardless of boxes dimensions. Example to play with here. Thanks !
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您能够将
标记更改为
那么这段 CSS 应该可以工作。
我认为最好对封闭的盒子使用更多的自动化,因为如果您更改容器盒子的大小,则需要较少的更改。
If you're able to change the
<span>
tag to a<div>
Then this piece of CSS should work.
I think it's better to use more automation for the enclosed box as less changes would be needed should you change the size of the container box.
如果您想要的话,您可以将
left:50px
添加到#abs
...You could add
left:50px
to#abs
if that's all you want...如果您要定义这样的尺寸(200px x 300px 和 300px x 400px),则可以按以下方式居中:
If you are going to define dimensions like that (200px x 300px and 300px x 400px), here's how it can be centered:
可以在 http://jsfiddle.net/NN68Z/96/ 查看我的解决方案
您 以下内容添加到 css 中
You can check at my solution here at http://jsfiddle.net/NN68Z/96/
I did the following to the css
这应该有效
This should work