让盒子在网页中居中的方法

让已知宽度和高度的盒子居中的两种方法,通过绝对定位实现,会跟着浏览器窗口的缩放不断调整位置,一直居中

方法一:通过绝对定位,定位时上边距与左边距都给50%,在利用margin减去当前盒子的一半宽度与高度

1
2
3
4
5
6
7
8
.box{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin: -50px 0 0 -50px;
}

方法二:通过绝对定位给4个方向都为0;用margin自动,实现居中

1
2
3
4
5
6
7
8
9
10
.box {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100px;
height: 100px;
margin: auto;
}

方法三:在不知道width、height的情况下,利用transform:translate(-50%, -50%)一样可以做到

1
2
3
4
5
6
7
8
.box {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
transform: translate(-50%, -50%);
}