以下demo都只是针对现代浏览器所做,未兼容低版本的IE以及其他非主流浏览器
html代码:
1 | <div id="box"> |
2 | <div id="child">我是测试DIV</div> |
3 | </div> |
使用绝对定位和负外边距对块级元素进行垂直居中
css代码:
1 | #box { |
2 | width: 300px; |
3 | height: 300px; |
4 | background: #ddd; |
5 | position: relative; |
6 | } |
7 | #child { |
8 | width: 150px; |
9 | height: 100px; |
10 | background: orange; |
11 | position: absolute; |
12 | top: 50%; |
13 | margin: -50px 0 0 0; |
14 | line-height: 100px; |
15 | } |
运行结果:

这个方法兼容性不错,但是有个缺点:必须提前知道被居中块级元素的尺寸,否则无法准确实现垂直居中
使用绝对定位和transform
css代码:
1 | #box { |
2 | width: 300px; |
3 | height: 300px; |
4 | background: #ddd; |
5 | position: relative; |
6 | } |
7 | #child { |
8 | background: #93BC49; |
9 | position: absolute; |
10 | top: 50%; |
11 | transform: translate(0, -50%); |
12 | } |
运行结果:

这个方法有一个非常明显的好处就是不必提前知道被居中元素的尺寸,因为transform中的translate偏移的百分比就是相对于元素自身的尺寸而言的。
另外一种使用绝对定位和负外边距进行垂直居中的方式
css代码:
1 | #box { |
2 | width: 300px; |
3 | height: 300px; |
4 | background: #ddd; |
5 | position: relative; |
6 | } |
7 | #child { |
8 | width: 50%; |
9 | height: 30%; |
10 | background: pink; |
11 | position: absolute; |
12 | top: 50%; |
13 | margin: -15% 0 0 0; |
14 | } |
运行结果

这种方式的原理实质上和前两种相同。补充的一点是:margin的取值也可以是百分比,这时这个值规定了该元素基于父元素尺寸的百分比,可以根据实际的使用场景来决定是用具体的数值还是用百分比。
绝对定位结合margin:auto
css代码:
1 | #box { |
2 | width: 300px; |
3 | height: 300px; |
4 | background: #ddd; |
5 | position: relative; |
6 | } |
7 | #child { |
8 | width: 200px; |
9 | height: 100px; |
10 | background: #A1CCFE; |
11 | position: absolute; |
12 | top: 0; |
13 | bottom: 0; |
14 | margin: auto; |
15 | line-height: 100px; |
16 | } |
运行结果:

这种实现方式的两个核心是:把要垂直居中的元素相对于父元素绝对定位,top和bottom设为相等的值,我这里设成了0,当然你也可以设为99999px或者-99999px无论什么,只要两者相等就行,这一步做完之后再将要居中元素的margin设为auto,这样便可以实现垂直居中了。
被居中元素的宽高也可以不设置,但不设置的话就必须是图片这种自身就包含尺寸的元素,否则无法实现。
使用padding实现子元素的垂直居中
css代码:
1 | #box { |
2 | width: 300px; |
3 | background: #ddd; |
4 | padding: 100px 0; |
5 | } |
6 | #child { |
7 | width: 200px; |
8 | height: 100px; |
9 | background: #F7A750; |
10 | line-height: 50px; |
11 | } |
运行结果:

这种实现方式非常简单,就是给父元素设置相等的上下内边距,则子元素自然是垂直居中的,当然这时候父元素是不能设置高度的,要让它自动被填充起来,除非设置了一个正好等于上内边距+子元素高度+下内边距的值,否则无法精确的垂直居中。
这种方式看似没有什么技术含量,但其实在某些场景下也是非常好用的。
