盒子居中的几种方法
拿下面的例子来说
1. 绝对定位 + 变换移动
.box{
position: relative;
width: 300px;
height: 300px;
background-color: pink;
}
.box>div{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
background-color: skyblue;
}
给子盒子绝对定位,定位到父盒子的中线上,这时子盒子的边在父盒子的中线上,所以还要在向左向右移动自身的50%,才能让子盒子和父盒子的中线相同。
2. 定位 + 外边距auto
.box{
position: relative;
width: 300px;
height: 300px;
background-color: pink;
}
.box>div{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: skyblue;
}
auto的意思是平分剩余空间,也就是上下左右都平分,盒子自然就居中了
上下左右值不为0时,要left值=right值,top值=bottom值,也可以实现居中,这样就更能体现出auto的作用,不过margin值会影响其他的盒子,所以还是值都设为0比较好。
3. flex布局
.box {
display: flex;
/*主轴居中*/
justify-content: center;
/*侧轴居中*/
align-items: center;
width: 300px;
height: 300px;
background-color: pink;
}
给父元素设置主轴居中、侧轴居中
暂时只学到了这几种,等再学到的话会继续补充的~