垂直对齐容器
我想将我的容器 div 垂直居中,就像它水平对齐一样,因为 margin: auto;
。我在谷歌上搜索了一些时间来了解如何做到这一点,但它似乎对我不起作用。也许有某种通用的方法可以做到这一点,就像水平居中的 margin: auto;
方法一样简单?因为我觉得很奇怪,我们生活在 2011 年,仍然没有简单的 css 命令来完成这项任务...
#container
{
margin: auto;
width: 960px;
height: 640px;
background-color: brown;
}
I would like to align my container div to center vertically just like it is aligning himself horizontally because of margin: auto;
. I've searched some time on google on how to do that but it does not seem to be working for me. Maybe there is some kind of universal way to do that, as easy as margin: auto;
method for horizontal centering? Because it seems for me very strange that we live in 2011 year and there is still no simple css command for doing this task...
#container
{
margin: auto;
width: 960px;
height: 640px;
background-color: brown;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关于垂直对齐,有大量教程,尤其是对于IE,需要特别小心。其中之一:使用 CSS 垂直居中内容。还有另一个答案此处。
There are tons of tutorials for vertical alignment, especially for IE, which needs special care. One of them: Vertically center content with CSS. Also another answer here.
还能更简单吗...
overflow:hidden
是隐藏出现的滚动条(IE6 为html
,IE5 为body
)。我不知道为什么会发生这种情况。但是,如果您希望在浏览器窗口较小时保持其可滚动,只需将高度设置为 639px 并删除
overflow:hidden
即可。Can it be even simpler...
The
overflow:hidden
is to hide the scrollbar that appears (html
for IE6 andbody
for IE5). I don't know why this happens.But if you want to keep it scrollable if the browser window is smaller, just make the height 639px and remove the
overflow:hidden
.如果您的 div 具有固定高度,您可以通过添加另一个具有负边距(主 div 高度的一半)的 div(带有浮动)来垂直对齐它,然后更改 div 的 CSS(添加
clear)。
另外不要忘记指定
html
和body
的 100% 高度,否则它不起作用。像这样:
CSS:
html:
If your div has a fixed height, you can align it vertically by adding another div (with a float) with a negative margin (half the height of the main div) and then alter your div's CSS (adding the
clear
).Also don't forget to specify the 100% height of the
html
andbody
, without that it doesn't work.Like this:
CSS:
html: