方法一:实现已知宽度的垂直水平居中
// 1
.wraper {
position: relative;
.box {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin: -50px 0 0 -50px;
}
}
方法二:实现未知宽度的垂直水平居中
// 2
.wraper {
position: relative;
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
}
方法三:实现未知宽度的垂直水平居中
// 3
.wraper {
.box {
display: flex;
justify-content:center; /*justify-content 用于设置或检索弹性盒子元素在主轴(横轴)方向上的对齐方式。*/
align-items: center; /*align-items 属性定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。*/
height: 100px;
}
}
方法四:实现未知宽度的垂直水平居中
// 4
.wraper {
display: table;
.box {
display: table-cell; /*此元素会作为一个表格单元格显示(类似 <td> 和 <th>)*/
vertical-align: middle; /*设置元素的垂直对齐方式*/
}
}