总结一下CSS的垂直居中布局,欢迎各位补充..
首先写个如下的html结构:
<div class="parent">
<div class="child"></div>
</div>
方法一:flex布局
.parent {
width: 100%;
height: 300px;
border: 1px solid red;
display: flex;
align-items: center;/*弹性盒子纵轴上居中*/
justify-content: center;/*弹性盒子横轴上居中*/
}
.child {
width: 60px;
height: 60px;
border: 1px solid springgreen;
}
.parent {
width: 100%;
height: 300px;
border: 1px solid red;
display: flex;
}
.child {
width: 60px;
height: 60px;
border: 1px solid springgreen;
margin: auto;
}
方法二:利用transform和绝对定位
.parent {
width: 100%;
height: 300px;
border: 1px solid red;
position: relative;
}
.child {
width: 60px;
height: 60px;
border: 1px solid springgreen;
transform: translate(-50%, -50%);
position: absolute;
top: 50%;
left: 50%;
}
方法三:利用calc和绝对定位
.parent {
width: 100%;
height: 300px;
border: 1px solid red;
position: relative;
}
.child {
width: 60px;
height: 60px;
border: 1px solid springgreen;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
方法四:利用absolute
.parent {
width: 100%;
height: 300px;
border: 1px solid red;
position: relative;
}
.child {
width: 60px;
height: 60px;
border: 1px solid springgreen;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
优点:摘自https://juejin.cn/post/6844903555342696456
- 1.跨浏览器,兼容性好(无需hack,可兼顾IE8~IE10);
- 2.无特殊标记,样式更精简;
- 3.自适应布局,可以使用百分比和最大最小高宽等样式;
- 4.居中时不考虑元素的padding值(也不需要使用box-sizing样式);
- 5.布局块可以自由调节大小;6.img的图像也可以使用
- 6.浏览器支持:Chrome、Firefox、Safari、Mobile Safari、IE8-10。 “完全居中”经测试可以完美地应用在最新版本的Chrome、Firefox、Safari、Mobile Safari中,甚至也可以运行在IE8~IE10上
方法五:利用inline-block+table-cell
.parent {
width: 100%;
height: 300px;
border: 1px solid red;
display: table-cell;
text-align: center;
vertical-align: middle;/*行内元素的基线相对于该元素所在行的基线的垂直对齐*/
}
.child {
width: 60px;
height: 60px;
border: 1px solid springgreen;
display: inline-block;
}
各个垂直居中都有相应的优缺点,例如浏览器兼容问题,本文没有详细说明,以后做深入研究,也欢迎各位批评指正!