垂直居中是布局中十分常见的效果之一,为实现良好的兼容性,PC端实现垂直居中的方法一般是通过绝对定位,table-cell,负边距等方法。有了css3,针对移动端的垂直居中就更加多样化。
笔者在这里总结了九种使用纯CSS实现水平垂直居中的方法
OK. Let’s see it!
最开始, 我们先设置几个盒子, 设置它们的统一样式为以下
| 12
 3
 4
 5
 6
 
 | .box {width: 300px;
 height: 300px;
 margin: 10px;
 box-shadow: 2px 3px 4px #000;
 }
 
 | 
方法1: table-cell
| 12
 3
 4
 
 | <!-- HTML --><div class="box box1">
 <span>垂直居中</span>
 </div>
 
 | 
整体的结构是相当简单的, css直接设置本身的宽高, 然后设置为table-cell,并将对齐方式设置为vertic-align就可以实现水平垂直居中了
| 12
 3
 4
 5
 6
 7
 
 | /* CSS */
 .box1{
 display: table-cell;
 vertical-align: middle;
 text-align: center;
 }
 
 | 
实际上table-cell的兼容性也是相当不错的, 可兼容至IE8+, 相当于将这个区块设置成了一个td
方法2: display: flex;
| 12
 3
 4
 5
 
 | .box2{display: flex;
 justify-content:center;
 align-items:Center;
 }
 
 | 
使用flex布局就非常简单了, 只需要设置两个属性即可, 存在的问题就是兼容性很有限, 虽然非常简单, 一般使用在移动端
方法3 绝对定位和负边距
这个在以前算是比较中规中矩的办法了, 首先需要将父盒子设置为相对定位, 子盒子设置为绝对定位
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | .box3 {position:relative;
 }
 .box3 span {
 position: absolute;
 width:100px;
 height: 50px;
 top:50%;
 left:50%;
 margin-left:-50px;
 margin-top:-25px;
 text-align: center;
 }
 
 | 
原理也非常简单, 将定位到中间距左部和顶部50%之后,需要减去自身的长宽的一半,就实现居中了
方法4: 绝对定位和0
这种方法常用于做蒙层和遮罩效果
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | .box4 span{width: 50%;
 height: 50%;
 background: #000;
 overflow: auto;
 margin: auto;
 position: absolute;
 top: 0;
 left: 0;
 bottom: 0;
 right: 0;
 }
 
 | 
利用绝对定位上下左右都设为0, 中间的子盒子设置margin为auto实现
方法5: translate
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | .box6 {position: relative;
 }
 .box6 span {
 position: absolute;
 top:50%;
 left:50%;
 width:100%;
 transform:translate(-50%,-50%);
 text-align: center;
 }
 
 | 
利用CSS3的转换效果, 将自身的位置向左上分别移动了50%, 也就是自身的一半, 就实现居中了 
方法6:display:inline-block
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | .box7 {text-align:center;
 font-size:0;
 }
 .box7 span {
 vertical-align:middle;
 display:inline-block;
 font-size:16px;
 }
 .box7:after {
 content:'';
 width:0;
 height:100%;
 display:inline-block;
 vertical-align:middle;
 }
 
 | 
这个方法就比较复杂一些了, 通过一个没有任何内容但高度为100%的伪类来进行占位, 根据vertical-align的特性, 来进行居中
方法7:display:flex和margin:auto
| 12
 3
 4
 5
 6
 7
 
 | .box8 {display: flex;
 text-align: center;
 }
 .box8 span {
 margin: auto;
 }
 
 | 
方法8:display:-webkit-box
| 12
 3
 4
 5
 6
 7
 
 | .box9 {display: -webkit-box;
 -webkit-box-pack:center;
 -webkit-box-align:center;
 -webkit-box-orient: vertical;
 text-align: center
 }
 
 | 
方法9:display:-webkit-box
这种方法,在 content 元素外插入一个 div。设置此 div height:50%; margin-bottom:-contentheight;。
content 清除浮动,并显示在中间。
| 12
 
 | <div class="floater"></div>  <div class="content"> Content here </div>
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | .floater {float:left;
 height:50%;
 margin-bottom:-120px;
 }
 .content {
 clear:both;
 height:240px;
 position:relative;
 }
 
 | 
(后两种居中方法摘自网络)