最好的解决方案(在我看来)是使用绝对定位将元素的左上角放置在 50%/50% 处,然后使用负边距将元素推回中心。唯一的缺点是您必须指定元素的宽度和高度。这是一个例子:
HTML:
<div id="centerme">
Hello, world!
</div>
CSS:
#centerme
{
position: absolute;
left: 50%;
top: 50%;
/* You must set a size manually */
width: 100px;
height: 50px;
/* Set negative margins equal to half the size */
margin-left: -50px;
margin-top: -25px;
background-color: cornflowerblue;
}
这是一个关于 jsfiddle 的演示:http://jsfiddle.net/UGm2V/
如果您确实需要居中的内容具有动态高度,则可以使用更高级的解决方案。请注意,它不适用于旧的 IE 浏览器。 HTML 如下:
<div id="outter-container">
<div id="inner-container">
<div id="centred">
<p>I have a dynamic height!</p>
<p>Sup!</p>
</div>
</div>
</div>
外部容器需要覆盖页面的宽度和高度。这是一个绝对定位的块元素。
内容器实际上是一张桌子!这是由display: table css 属性决定的。这里的胜利是您实际上不需要任何表格 HTML。
#centred div 是最后一个必需的元素。它仍然覆盖 100% 的页面宽度和高度,但放置在其中的任何内容都将垂直和水平居中。这是您需要的 css,并附有说明:
/*
An outter container is needed because the table
won't cover the page width and height on it's own
*/
#outter-container
{
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
/*
The inner container is a table which is set to
cover the width and height of the page.
*/
#inner-container
{
display: table;
width: 100%;
height: 100%;
}
/*
This table cell will cover 100% of the page width
and height, but everything placed inside it will
be placed in the absolute centre.
*/
#centred
{
display: table-cell;
vertical-align: middle;
text-align: center;
}
当然,这里还有一个 jsfiddle 演示:http://jsfiddle.net/N7ZAr/3/