实现盒子水平垂直居中的方法
以下仅限个人的经验所得,希望对你有所帮助
.f 为父盒子 .s 为子盒子
方法一:当盒子可以设置固定宽高的时候,
…
.f {
width: 500px;
height: 500px;
background-color: #000;
position: relative;
}
.s {
width: 100px;
height: 100px;
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
方法二: 一种简洁直观的方法
…
.f {
width: 500px;
height: 500px;
background-color: #000;
position: relative;
}
.s {
width: 100px;
height: 100px;
background-color: #fff;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin :auto;
}
方法三 位移
…
.f {
width: 500px;
height: 500px;
background-color: #000;
position: relative;
}
.s {
width: 100px;
height: 100px;
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法四 flex布局
…
.f {
width: 500px;
height: 500px;
background-color: #000;
display :flex;
justify-content :center;
align-items :center;
}
.s {
width: 100px;
height: 100px;
background-color: #fff;
}
加油!

本文详细介绍了使用CSS实现盒子在父容器中水平垂直居中的四种方法,包括利用绝对定位配合margin、利用绝对定位结合transform、简洁的margin auto方法以及现代的flex布局方案,适合初学者及需要快速回顾的前端开发者。
1695

被折叠的 条评论
为什么被折叠?



