1. 使用flex布局
在父容器中设置
.container{
display: flex;
justify-content: center;
align-items: center
}
2. 绝对定位
分为已知宽高和未知宽高两种情况
已知宽高都是100px,设置自身为绝对定位(absolute),top和left为50%,margin-left、margin-top为自身的一半,也就是50px
.item {
width: 100px;
height: 100px;
border: 1px solid red;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
未知宽高
/*使用transform*/
.item {
border: 1px solid red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%)