方案一:
盒子有设置宽高,直接margin: auto;
方案二:用position,left、right、top、bottom加margin调整
<style>
.a{
position: relative;
width: 600px;
height: 600px;
border: 1px solid black;
}
.box{
position: absolute;
width: 200px;
height: 200px;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: pink;
margin: auto;
}
</style>
<div class="a">
<div class="box"></div>
</div>
方案三:position + transform:translate,水平垂直方向都可居中,例如
<style>
body{
/* position: relative; */
margin: 0;
}
.a{
position: relative;
width: 600px;
height: 600px;
border: 1px solid black;
}
.box{
position: absolute;
width: 200px;
height: 200px;
top: 50%; /*盒子左上角的那个点在页面正中间*/
left: 50%;
background-color: pink;
transform: translateX(-50%) translateY(-50%);/*不需要知道盒子宽度*/
}
</style>
<div class="a">
<div class="box"></div>
</div>
方案四:用弹性盒模型flex
<style>
body{
/* position: relative; */
margin: 0;
}
.a{
display: flex;
justify-content: center; /*水平居中*/
align-items: center; /*垂直居中*/
height: 600px;
width: 600px;
border: 1px solid black;
}
.box{
width: 200px;
height: 200px;
background-color: pink;
}
</style>
<div class="a">
<div class="box">
</div>
</div>