1、水平居中的方法:
① 若是针对inline, 内联块inline-block, 内联表inline-table, inline-flex元素及img,span,button等元素
父元素设置text-align:center;
或者用绝对定位、弹性布局、grid网格布局实现;
② 不定宽块状元素
设置margin:0 auto;
或者用绝对定位、弹性布局、grid网格布局、table表布局实现;
grid网格布局:阮一峰 CSS Grid 网格布局教程:CSS Grid 网格布局教程 - 阮一峰的网络日志
.farther {display: grid;justify-content: center;}
table表布局:
.father {display: table;}.children {display: table-cell;text-align: center; }
2、垂直居中的方法:
① 若为单行内联(inline-)元素:
通过设置内联元素的高度(height)和行高(line-height)相等,从而使元素垂直居中;
或者用绝对定位、弹性布局、table表布局、grid网格布局实现;
② 不定宽块状元素:
绝对定位、弹性布局、table表布局、grid网格布局;
grid网格布局:
.farther {display: grid;justify-content: center;align-content: center;}
table表布局:
.father {display: table;}.children {display: table-cell;vertical-align: middle;text-align: center; }
3、总结
CSS 垂直居中有哪些实现方式?- 题目详情 - 前端面试题宝典
4、水平垂直居中的实现
① 绝对定位 +translate
利用绝对定位,先将元素的左上角通过 top:50%和 left:50%定位到页面的中心,然后再通过 translate 来调整元素的中心点到页面的中心。 该方法需要考虑浏览器兼容问题。
.parent {position: relative;}.child {position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);}
②绝对定位 +margin: auto
利用绝对定位,设置四个方向的值都为 0,并将 margin 设置为 auto。由于宽高固定,因此对应方向实现平分,可以实现水平和垂直方向上的居中。该方法适用于盒子有宽高的情况。
.parent {position: relative;}.child {position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto;}
③ 绝对定位 +margin: 负值
利用绝对定位,先将元素的左上角通过 top:50%和 left:50%定位到页面的中心,然后再通过margin 负值来调整元素的中心点到页面的中心。该方法适用于盒子宽高已知的情况。
.parent {position: relative;}.child {width: 100px;height: 100px;position: absolute;left: 50%;top: 50%;margin-left: -50px;margin-top: -50px;}
④ flex布局
利用flex布局,通过align-items:center和 justify-content:center设置容器的垂直和水平方向上为居中对齐,然后它的子元素也可以实现垂直和水平的居中。该方法要考虑兼容的问题,该方法在移动端用的较多。
.parent {display: flex;justify-content: center;align-items: center;}