1、兼容性不错,但是需要提前知道元素的高度宽度,往往需要通过JS获取
.content {
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 400px;
margin-top: -200px; //高度的一半
margin-left: -150px; //宽度的一半
}
2、【推荐】css3的一种用法,使用transform代替margin. transform中translate偏移的百分比值是相对于自身大小的
.content {
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 400px;
transform: translate(-50%,-50%); // 50%为尺寸的一半
}
3、使用margin:auto实现左右自动居中,上下居中通过定位等其他方法实现
.content{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
4、使用flex布局
.content{
display: flex;
align-item: center;
justify-content: center;
}