css实现盒子居中方案-新手向
盒子居中时ccs一个重要的知识点,常见的类型有不定宽高和定宽高的盒子居中,这里总结了几种常见的居中方法,便于新人学习
html基础结构
<div class="box">
<div class="son"></div>
</div>
限制宽高
1、利用margin负值移动盒子
子盒子定位后会处于父盒子中心右下方,这时使子盒子向相反方向位移子盒子宽高的一半实现居中
.box {
width: 200px;
height: 200px;
background-color: pink;
/* 给盒子添加定位,子绝父相 */
position: relative;
}
.son {
width: 50px;
height: 50px;
background-color: beige;
position: absolute;
/* 左上定位50%后盒子会再中心多右下位置 */
left: 50%;
top: 50%;
/* 这时用margin向反方向移动子盒子的宽高一半使盒子居中 */
margin-left: -25px;
margin-top: -25px;
}
这种方法在子盒子宽高变化时margin位移值不变会使盒子偏移中心
不限制宽高
2、绝对定位法
绝对定位的四个方向值设为0,设置magin:auto;让盒子挤到中间
.box {
width: 200px;
height: 200px;
background-color: pink;
/* 同样给盒子添加定位,子绝父相 */
position: relative;
}
.son {
width: 50px;
height: 50px;
background-color: beige;
position: absolute;
/* 上下左右为零盒子会被挤到中间 */
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
不限制盒子宽高,盒子会被挤到中间
3、绝对定位+transform
同方法一,但transform基于自身宽高位移,始终位移自身的一半
.box {
width: 200px;
height: 200px;
background-color: pink;
/* 给盒子添加定位,子绝父相 */
position: relative;
}
.son {
width: 50px;
height: 50px;
background-color: beige;
position: absolute;
/* 左上定位50%后盒子会再中心多右下位置 */
top: 50%;
left: 50%;
/* transform属性基于自身宽高进行平移 */
transform: translate(-50%, -50%);
}
相比一种方法transform始终平移盒子宽高的一半,盒子宽高的变化不影响盒子居中
4、flex居中法
利用弹性盒子的justify-content和align-items属性进行居中
.box {
width: 200px;
height: 200px;
background-color: pink;
/* 设置弹性盒子 */
display: flex;
/* 主轴居中和侧轴居中 */
justify-content: center;
align-items: center;
}
.son {
width: 50px;
height: 50px;
background-color: beige;
}
代码最少,但子盒子不能有兄弟元素
5、无宽高的盒子居中
最灵活的方式,只需让左右和上下方位的百分值相等,盒子的大小取决于百分值的大小
.box {
width: 200px;
height: 200px;
background-color: pink;
/* 设置定位子绝父相 */
position: relative;
}
.son {
background-color: beige;
position: absolute;
/* 左右方位和上下方位的值必须一样 */
left: 25%;
right: 25%;
top: 30%;
bottom: 30%;
}
转载自:https://juejin.cn/post/7273684196634968083