一到三种方法都会配合定位来使用, 所以当子盒子添加了绝对定位; 那么父盒子一定要加上相对定位(简称父绝子相).
第一种:
使用定位配合margin的负值使用, 注意这里的margin负值是对于子盒子自身的宽高而言的.
<style>
.father {
position: relative;
width: 400px;
height: 400px;
margin: 100px auto;
background-color: pink;
}
.son {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-left: -100px;
margin-top: -100px;
background-color: red;
}
</style>
<body>
<div class = "father">
<div class = "son"></div>
</div>
</body>
第二种:
使用定位和transform位移一起使用, 注意transform位移的百分比值也是子盒子自身的宽高的一半.
<style>
.father {
position: relative;
width: 400px;
height: 400px;
margin: 100px auto;
background-color: pink;
}
.son {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
background-color: red;
transform: translate(-50%, -50%);
/* 位移的百分比相对于盒子的自身宽高而言 */
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
第三种:
将top, left, right和bottom值全部设置为0, 然后使用margin: auto;
<style>
.father {
position: relative;
width: 400px;
height: 400px;
margin: 100px auto;
background-color: pink;
}
.son {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 200px;
height: 200px;
margin: auto;
background-color: red;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
第四种:
给父元素设置flex布局, 然后设置主轴和侧轴实现子盒子在父元素中垂直水平居中
<style>
.father {
display: flex;
width: 400px;
height: 400px;
justify-content: center; // 在主轴上居中
align-items: center; // 在侧轴上居中
margin: 100px auto;
background-color: pink;
}
.son {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>