一 定位+margin
将元素设置绝对定位 然后上下走下都为0 margin:auto(自动)
<style>
.box{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
<div class="box"></div>
二 定位+平移
给元素设置定位 top 和left各为50% 再通过向左向上平移元素的50%来让元素水平垂直居中
<style>
.box{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
<div class="box"></div>
三 flex弹性盒子
通过主轴和交叉轴剧中的方式让元素居中justify-content: center; align-items: center;
<style>
.father{
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.box{
width: 200px;
height: 200px;
background-color: red;
}
</style>
<div class="father">
<div class="box"></div>
</div>