总结一下了解的css实现水平垂直居中的方法。
可以在codepen上进行测试。
原始代码
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | <html>
 <body>
 <div class="father">
 <div class="son"></div>
 </div>
 </body>
 
 </html>
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | .father {border: solid 1px;
 width: 300px;
 height: 300px;
 }
 
 .son {
 background: #e4393c;
 width: 100px;
 height: 100px;
 }
 
 | 
具体实现
flex 方法1——适用于未知宽高
给父元素加弹性盒属性,加justify-content , align-items属性即可
| 12
 3
 4
 5
 
 | .father {display: flex;
 justify-content: center;
 align-items: center;
 }
 
 | 
flex 方法2——适用于已知宽高
给父元素加弹性盒属性,子元素加 margin:auto
| 12
 3
 4
 5
 6
 
 | .father {display: flex;
 }
 .son {
 margin:auto;
 }
 
 | 
父元素相对定位,子元素绝对定位,并且使用transform平移实现
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | .father {position: relative;
 }
 .son {
 position: absolute;
 left: 50%;
 top: 50%;
 transform: translate(-50%, -50%);
 }
 
 
 | 
定位,父相子绝,配合margin属性
父元素相对定位,子元素绝对定位,同时上下左右为0,同时加上margin:auto
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | .father {position: relative;
 }
 .son {
 position: absolute;
 margin: auto;
 left: 0;
 right: 0;
 top: 0;
 bottom: 0;
 }
 
 | 
父元素display: table-cell,子元素display: inline-block;
将父元素转为一个表格单元,子元素转为行内块
| 12
 3
 4
 5
 6
 7
 8
 
 | .father {display: table-cell;
 text-align: center;
 vertical-align: middle;
 }
 .son {
 display: inline-block;
 }
 
 | 
纯定位方式实现
父相子绝,子元素 left , right 各50%,再使用 margin-left , margin-top , 移动子元素自身宽高的一半
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | .father {position: relative;
 }
 .son {
 position: absolute;
 left: 50%;
 top: 50%;
 margin-left: -50px;
 margin-top: -50px;
 }
 
 | 
grid 方法1
| 12
 3
 4
 5
 
 | .father {display: grid;
 align-content: center;
 justify-content: center;
 }
 
 | 
grid 方法2
父元素加display: grid;,子元素加align-self: center; justify-self: center;即可
| 12
 3
 4
 5
 6
 7
 
 | .father {display: grid;
 }
 .son {
 align-self: center;
 justify-self: center;
 }
 
 | 
补充
| 12
 3
 
 | <div class="father"><span class="son">son</span>
 </div>
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | .father{background-color: red;
 height: 100px;
 text-align:center;
 }
 
 .son{
 background-color: pink;
 line-height:100px;
 }
 
 | 
参考
写在最后
关于浏览器兼容性,
- 完全不考虑并且布局较复杂,推荐使用grid(grid 就是为了解决复杂布局的)
- 完全不考虑,flex和grid都是不错的选择;
- 需要考虑移动端,建议使用flex而不是grid;
- 需要兼容老版本的浏览器,建议使用纯定位方式实现