1、父元素设置为弹性盒子
<div class="box">
<div class="box-cont"></div>
</div>
<style>
.box{
width: 100vw;
height: 100vh;
display:flex;
justify-content:center;
align-items: center;
}
.box-cont{
width: 100px;
height: 100px;
color: red;
}
</style>
2、绝对定位:盒子有固定长宽,将div的上下左右的坐标都设置为0,然后margin设置为auto,div即会居中展示,
<div class="box"></div>
<style>
.box{
position:absolute;
width:10px;
height:10px;
background:blue;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
}
</style>
3、绝对定位:盒子长宽不确定,使用transform方式进行居中,transform即是变形使用他的translate属性。
<div class="box"></div>
<style>
.box{
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
background:red;
}
</style>