1.利用定位子绝父相+外边距margin:
* {
margin: 0;
padding: 0;
}
.father {
/* 父盒子相对定位 /
position: relative;
width: 800px;
height: 600px;
background-color: pink;
}
.son {
/ 子盒子绝对定位 /
position: absolute;
/ 子盒子往下走父盒子一半的高度 /
top: 50%;
/ 子盒子往右走父盒子一半的宽度 /
left: 50%;
/ 子盒子往左走自身宽度的一半 /
margin-left: -100px;
/ 子盒子往上走自身高度的一半 */
margin-top: -100px;
width: 200px;
height: 200px;
}
3.利用flex实现盒子居中:
<style>
* {
margin: 0;
padding: 0;
}
.father {
/* 先让父盒子变弹性容器,子盒子变弹性盒子 */
display: flex;
width: 800px;
height: 600px;
background-color: pink;
/* 主轴居中 */
justify-content: center;
/* 侧轴居中 */
align-items: center;
}
.son {
width: 200px;
height: 200px;
background-color: red;
}
</style>