这是一个很常见的样式布局,网上也有很多的实现方式,本文主要是针对一些比较常用到的方法做一下总结,记录一下。
现有实现方式大致的思路归纳为以下几种:
- 固定宽高居中- absolute + margin auto
- absolute + 负 margin
- absolute + calc
 
- 不定宽高居中-  lineheight
- flex
- absolute + transform
- grid
- table-cell
 
公共代码(后面代码都基于这里)
| 12
 3
 
 | <div class="out"><div class="inner">水平垂直居中</div>
 </div>
 
 | 
实现的效果:

absolute + margin auto
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | .out {width: 500px;
 height: 500px;
 border: 1px solid #000;
 position: relative;
 }
 
 .inner {
 background-color: blueviolet;
 width: 300px;
 height: 300px;
 position: absolute;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 margin: auto;
 }
 
 | 
absolute + 负 margin
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 
 | .out {width: 500px;
 height: 500px;
 border: 1px solid #000;
 position: relative;
 }
 
 .inner {
 background-color: blueviolet;
 width: 300px;
 height: 300px;
 position: absolute;
 top: 50%;
 left: 50%;
 margin-left: -150px;
 margin-top: -150px;
 }
 
 | 
absolute + calc
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | .out {width: 500px;
 height: 500px;
 border: 1px solid #000;
 position: relative;
 }
 
 .inner {
 background-color: blueviolet;
 width: 300px;
 height: 300px;
 position: absolute;
 top: calc(50% - 150px);
 left: calc(50% - 150px);
 }
 
 | 
lineheight
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 
 | .out {width: 500px;
 height: 500px;
 border: 1px solid #000;
 line-height: 500px;
 text-align: center;
 font-size: 0px;
 }
 
 .inner {
 font-size: 16px;
 background-color: blueviolet;
 display: inline-block;
 vertical-align: middle;
 line-height: initial;
 
 
 
 text-align: center;
 }
 
 | 
flex
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | .out {width: 500px;
 height: 500px;
 border: 1px solid #000;
 display: flex;
 justify-content: center;
 align-items: center;
 }
 
 .inner {
 background-color: blueviolet;
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | .out {width: 500px;
 height: 500px;
 border: 1px solid #000;
 position: relative;
 }
 
 .inner {
 background-color: blueviolet;
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 }
 
 | 
grid
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | .out {width: 500px;
 height: 500px;
 border: 1px solid #000;
 display: grid;
 }
 
 .inner {
 background-color: blueviolet;
 align-self: center;
 justify-self: center;
 }
 
 | 
table-cell
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | .out {width: 500px;
 height: 500px;
 border: 1px solid #000;
 display: table-cell;
 text-align: center;
 vertical-align: middle;
 }
 
 .inner {
 background-color: blueviolet;
 display: inline-block;
 }
 
 | 
好了,基本上就这些了;还有些不怎么用到的就没去整理了。
- PC 端:考虑兼容性的话推荐使用 absolute+负 margin 和table-cell; 否则直接 flex。
- 移动端:首推flex。