<div class="box"></div>
<style type="text/css">
// 方法一
.box{
width: 400px;
height: 400px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
margin: -200px 0 0 -200px
}
// 方法二
.box{
width: 400px;
height: 400px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
// 移动盒子自身宽高的一半
transform: translate(-50%,-50%);
}
// 方法三
.box{
width: 400px;
height: 400px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
【 总结 】盒子水平垂直居中
最新推荐文章于 2025-05-16 09:49:31 发布
本文介绍了三种不同的CSS方法来实现一个400px*400px的粉色背景盒子在页面中垂直和水平居中:1)通过设置绝对定位和负边距;2)使用transform的translate属性;3)利用自动外边距。这些方法适用于不同场景,帮助开发者更好地理解和掌握网页布局技巧。
428

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



