第一种:flex布局 让他主轴侧轴居中
.father {
position: relative;
width: 500px;
height: 300px;
margin: 100px auto;
border: 1px solid #000;
/* 第一种盒子居中的方法 flex布局 缺点:盒子无法覆盖其他标准流 */
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 200px;
height: 100px;
background-color: pink;
}
第二种盒子居中方法:margin+定位(子绝父相) 缺点:盒子的宽高要固定
.son {
width: 200px;
height: 100px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
/* 移动当前盒子子元素宽高的一半
第二种盒子居中方法margin+定位(子绝父相) 缺点:盒子的宽高要固定 */
margin-left: -100px;
margin-top: -50px;
第三种盒子居中方法 位移+定位(子绝父相) 推荐用这个方法
.son {
width: 200px;
height: 100px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
/* 第三种盒子居中方法 位移+定位(子绝父相) 推荐用这个方法 */
transform: translate(-50%,-50%);
}
第四种盒子居中方法 定位+margin来实现
.son{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 100px;
background-color: pink;
}