废话不多说直接上代码
第一种:
#box{
width: 100px;
height: 100px;
background: pink;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
第二种
#box{
width: 100px;
height: 100px;
background: pink;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
注:因为left和top定位的点是box的左上角居中,所以需要一个margin拉回去
第三种
和第二种类似,只不过是第三种方法即使在不确定盒子宽高的情况下也可以用
#box#box{
width: 100px;
height: 100px;
background: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate3d(-50%,-50%,0);
}
第四种
这个主要是利用flex布局,给父级元素垂直居中和水平居中
#boxfathder{
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
background: red;
}
#box{
width: 100px;
height: 100px;
background: pink;
}
效果如图: