最好的解决方案(在我看来)是使用绝对定位将元素的左上角放置在50%/ 50%,然后使用负边距将元素推回到中心.唯一的缺点是您必须指定元素的宽度和高度.这是一个例子:
HTML:
Hello, world!
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;
}
如果您确实需要居中内容具有动态高度,那么就有了更高级的解决方案.要知道它在旧的IE浏览器中不起作用. HTML如下:
I have a dynamic height!
Sup!
外部容器需要覆盖页面的宽度和高度.它是具有绝对定位的块元素.
内部容器实际上是一张桌子!这是由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;
}