准备工作,假设有如下html
<div class="wrapper">
<div class="box">
</div>
</div>
需要设置宽高
1.position + 负margin
.wrapper{
position:relative;
}
.box{
width:100px;
height:100px;
position:absolute;
left:50%;
top:50%;
margin-left: -50px;
margin-top: -50px;
}
2. position + margin:auto
.wrapper{
position:relative;
}
.box{
width:100px;
height:100px;
position:absolute;
left:0
top:0;
right:0;
bottom:0;
margin:auto;
}
3.position + calc()
.wrapper{
position:relative;
}
.box{
width:100px;
height:100px;
position:absolute;
left:calc(50% - 50px) ;
top:calc(50% - 50px) ;
}
不需要设置宽高
1.position + transform
.wrapper{
position:relative;
}
.box{
width:100px;
height:100px;
position:absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2.flex布局
.wrapper{
display:flex;
align-items:center;
justify-content:center;
}
本文介绍五种实现元素在页面上居中的CSS技巧,包括使用负margin、auto margin、calc()函数、transform属性以及flex布局,适用于不同场景的需求。
3023

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



