本文已参与「新人创作礼」活动,一起开启掘金创作之路。
元素垂直居中
<div class="box-con">
<div class="box-son"></div>
</div>
方法1:弹性盒子模型
.box-con{
display: flex; /* flex布局 */
justify-content:center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
方法2:绝对定位+转换
.box-con{
position: relative; /* 相对定位 */
}
.box-son{
position: absolute; /* 绝对定位 */
left: 50%;
top: 50%;
transform: translate(-50%,-50%); /* 2D转换:移动translate*/
transform: translateX(-50%);
transform: translateY(-50%);
}
方法3:绝对定位+外边距
.box-con{
position: relative; /* 相对定位 */
}
.box-son{
position: absolute; /* 绝对定位 */
left: 50%;
top: 50%;
margin-top: -25px; /* 外边距=负的盒子宽度的50%*/
margin-left: -25px;
}
方法4:表格单元格
.box-con{
display: table-cell; /* 表格模式,让标签元素以表格单元格的形式呈现,使元素类似于td标签 */
text-align:center; /* 水平居中 */
vertical-align: middle; /* 垂直居中 */
}
.box-son{
display: inline-block; /* 行内块模式 */
}
方法5:绝对定位+外边距
.box{
width: 200px;
height: 200px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}