1.定位+transform: translate(-50%, -50%)
<style>
.box1{
width: 500px;
height: 450px;
background-color: pink;
position: relative;
}
.box2{
width: 300px;
height: 300px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
<div class="box1">
<div class="box2">
</div>
</div>
2.flex 弹性布局居中
给父盒子设置 display:flex; justify-content:center; align-items:center;
<style>
.box1{
width: 500px;
height: 450px;
background-color: pink;
display: flex;
justify-content: center;
align-items: center;
}
.box2{
width: 300px;
height: 300px;
background-color: blue;
}
</style>
<div class="box1">
<div class="box2">
</div>
</div>
3.margin: auto;
<style>
.box1{
width: 500px;
height: 450px;
background-color: pink;
position: relative;
}
.box2{
width: 300px;
height: 300px;
background-color: blue;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
<div class="box1">
<div class="box2">
</div>
</div>