让盒子在网页中居中的方法
分类: CSS3 5307 2
让已知宽度和高度的盒子居中的两种方法,通过绝对定位实现,会跟着浏览器窗口的缩放不断调整位置,一直居中
方法一:通过绝对定位,定位时上边距与左边距都给50%,在利用margin减去当前盒子的一半宽度与高度
.box{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
margin: -50px 0 0 -50px;
}
方法二:通过绝对定位给4个方向都为0;用margin自动,实现居中
.box {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100px;
height: 100px;
margin: auto;
}
方法三:在不知道width、height的情况下,利用transform:translate(-50%, -50%)一样可以做到
.box {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
transform: translate(-50%, -50%);
}
共 2 条评论关于 “让盒子在网页中居中的方法”