CSS 的水平居中和垂直居中

在 CSS 中,文本的水平居中可以简单地用 text-align: center 来实现。因此,再加上 margin: auto 就可以实现 DIV 元素的水平居中。例如:

<!DOCTYPE html>
<html>
<head>
<title>horizontal center in css</title>
<style type='text/css'>
#parent {
   500px;
  height: 500px;
  text-align: center;
  border: 1px solid black;
}
#child {
   300px;
  margin: auto; 
  text-align: left;
}
</style> 
</head>
<body>
  <div id="parent">
    <div id="child">Hello World! Hello World! Hello World! Hello World! Hello World!</div>
</div>
</body>
</html>

垂直居中稍微麻烦一些,因为 margin-top 和 margin-bottom 为 auto 在大多数情形等同于 0。但我们还是有不少办法的。例如:

<!DOCTYPE html>
<html>
<head>
<title>vertical center in css</title>
<style type='text/css'>
#parent {
   300px;
  height: 300px;
  display: table;
  border: 1px solid black;
}
#child {
  display: table-cell;
  vertical-align: middle; 
  text-align: center;
}
</style> 
</head>
<body>
  <div id="parent">
    <div id="child">Hello World! Hello World! Hello World! Hello World! Hello World!</div>
</div>
</body>
</html>

这种方法对 IE6 和 IE7 无效。暂时无需用到这个,就不再深入研究了。

更新:最近发现了更简单的水平且垂直居中的方法(见参考资料[B]),如下:

.absolute-center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

虽然也不支持 IE6 和 IE7,但 IE6 和 IE7 是该被抛弃了。

[1] 6 Methods For Vertical Centering With CSS
[2] Vertically Center Multi-Lined Text
[3] How to vertically and horizontally center text
[4] CSS未知高度垂直居中
[5] inline-block 实现的浏览器通用居中
[6] CSS-Tricks - Centering in the Unknown
[7] Alice/solutions/vertical-horizoncal
[8] 大小不固定的图片、多行文字的水平垂直居中 - 张鑫旭
[9] CSS的提示与窍门 - 居中
[A] Dead Center Example
[B] Absolute Horizontal And Vertical Centering In CSS | Smashing Coding

[YAML] Update: 2013-12-02 18:35:00

原文地址:https://www.cnblogs.com/zoho/p/2522209.html