HTML 元素,水平、垂直居中

举个栗子:如何将 div 盒子中的一个 p 元素,水平、垂直居中?

水平居中

用 CSS 将 div 的对齐方式设为居中即可。

div {
    text-align: center;
}

垂直居中

在 p 元素前插入一个空的 span(设定 class 为 helper),给 helper 类和 p 元素设定如下 CSS:

.helper {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

p {
    display: inline-block;
    vertical-align: middle;
}

原理:

  1. When you have two inline-block elements near each other, you can align each to other's side, so with vertical-align: middle you'll get something like this:
    Two aligned blocks
  2. When you have a block with fixed height (in px, em or other absolute unit), you can set the height of inner blocks in %.
  3. So, adding one inline-block with height: 100% in a block with fixed height would align another inline-block element in it (<img/> in your case) vertically near it.

兼容低版本IE

上面的垂直居中在 IE6~IE8 上不能正常显示,因为 IE8 以下不支持 inline-block。
在 CSS 中增加如下代码即可:

    *display:inline;
    zoom:1;

完整示例

在线演示:http://demo.baimoz.me/simple/centerDemo/

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>水平垂直居中</title>
        <style>
            div {
                height: 400px;
                width: 400px;
                border: 1px solid #ccc;
                background: #ff0;
                text-align: center;
            }
            .poem {
                display: inline-block;
                vertical-align: middle;
                *display:inline;
                zoom:1;
            }
            .helper {
                display: inline-block;
                height: 100%;
                vertical-align: middle;
            }
        </style>
    </head>
    <body>
        <div>
            <span class="helper"></span>
            <p class="poem">春有百花秋有月,<br>夏有凉风冬有雪。<br>若无闲事挂心头,<br>便是人间好时节。</p>
        </div>
    </body>
</html>

参考资料