内容垂直居中

在工作中,经常会遇到需要让某个内容在父级元素中垂直居中的问题。本篇对垂直居中进行统一的总结,后期不断完善。

子级元素在父级元素中垂直居中有以下几种方法:

【根据经验,PC端比较常用方法4,移动端比较常用方法2】

html结构:

1
2
3
<div class="outbox">
<div class="inbox">测试文字<p>测试测试</p></div>
</div>


子级无高度

方法1

**兼容IE8+ 【查看demo】

1
2
3
4
5
6
7
.outbox{
display: table;
}
.inbox{
display: table-cell;
vertical-align: middle;
}

这种方法的弊端:

  1. outbox不支持overflow:hidden属性,只能给outbox嵌套一个父级来设置overflow:hidden属性
  2. inbox默认宽和高均为父级的100%,不支持自定义的宽和高。可以给它添加一个子级来限制宽和高。

此方法兼容IE6-7的hack: 查看demo

注:以上代码如果想兼容IE6-7,需要在inbox里面再嵌套一个div例如命名为content,然后添加如下hack即可:(以下代码是只兼容IE6-7的垂直居中代码)

1
2
3
4
5
6
7
8
9
10
11
.outbox{
*position: relative;
}
.inbox{
*position: absolute;
*top: 50%;
}
.content{
*position: relative;
*top: -50%;
}

方法2(移动端最佳)

**只兼容IE9+ 查看demo

1
2
3
4
5
6
7
8
9
.outbox{
position: relative;
}
.inbox{
position: absolute;
left: 50%; // 水平也居中
top: 50%;
transform: translate(-50%,-50%);
}

方法3

**所有浏览器均兼容 查看demo

(此方法貌似并不实用,仅供了解)此方法在IE8+中和方法1是一样的,在IE6-7中,inbox必须是行内元素,并且inbox后面还得加上一个空的行内元素。
结构示例:

1
2
3
4
5
6
<div class="outbox">
<span class="inbox">
测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试
</span>
<b></b>
</div>

方法4 (PC端最佳)

**兼容IE8+ 查看demo

1
2
3
4
5
6
7
8
9
10
11
.inbox{
display: inline-block;
vertical-align: middle;
}
.outbox:before{
content: "";
width: 0;
height: 100%;
display: inline-block;
vertical-align: middle;
}

此方法兼容IE6-7的hack: 查看demo

由于IE6-7不支持伪类和块元素的inline-block,所以此方法若想兼容IE6-7,需要在inbox的前面或后面加上一个空的div例如命名为empty,然后写hack即可。(也可以再嵌套一个content然后用方法1中的hack)

1
2
3
4
5
6
7
8
9
10
.inbox,.empty{
display: inline-block;
vertical-align: middle;
*display: inline;
*zoom: 1;
}
.empty{
height: 100%;
*width: 1px;
}

方法5

兼容IE8+。但是貌似只兼容文档头为HTML5类型的文件,例如XHTML就不兼容。(可用于移动端)。

1
2
3
4
5
6
7
8
9
.outbox{
line-height: 400px; // 行高等于高度
}
.inbox{
display: inline-block;
*display: inline;
vertical-align: middle;
line-height: 2; // 如果有文字,行高必须定义否则文字会跑出去
}

子级有高度

方法6

所有浏览器均兼容

1
2
3
4
5
6
7
8
9
outbox{
position: relative;
}
inbox{
height: 100px;
position: absolute;
top: 50%;
margin-top: -50px; // 高度的一半
}

方法7

兼容IE8+ 查看demo

1
2
3
4
5
6
7
8
9
10
.inbox{
height: 100px;
}
.outbox:before{
content: "";
display: block;
width: 100%;
height: 50%;
margin-bottom: -50px; // 高度的一半
}

此方法兼容IE6-7的解决方案:

由于IE6-7不支持伪类,所以此方法若想兼容IE6-7,需要在inbox的前面加上一个空的div例如命名为empty,css代码如下。

1
2
3
4
5
6
7
.inbox{
height: 100px;
}
.empty{
height: 50%;
margin-bottom: -50px; // 高度的一半
}

父级无高度

如果父级outbox的高度是自适应的,那么想要垂直居中,直接给子级inbox加相同的上下内边距padding即可!

—— end —— 注:水平有限,难免有误,如有错误欢迎指出!