两种以上方式实现已知或者未知宽度的垂直水平居中
/** 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;
align-items: center;
height: 100px;
}
}
/** 4 **/
.wraper {
display: table;
.box {
display: table-cell;
vertical-align: middle;
}
}
本文介绍了四种不同的CSS技术,用于在已知或未知宽度的情况下实现元素的垂直和水平居中对齐。方法包括使用绝对定位配合margin负值、transform translate、flexbox布局以及display: table-cell。这些方法适用于现代浏览器,提供了灵活且兼容的解决方案。
1259

被折叠的 条评论
为什么被折叠?



