元素水平垂直居中方法
方案一、弹性盒子沿主轴和侧轴居中
.outer {
width: 400px;
height: 400px;
background-color: #888;
display: flex;
justify-content: center;
align-items: ceter;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
}
方案二、弹性盒子设置自动的边距
.outer {
width: 400px;
height: 400px;
background-color: #888;
display: flex;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
margin: auto;
}
方案三、定位设置子元素左上角位于父元素中心,然后通过translate参考自身宽高,分别移动-50%
.outer {
width: 400px;
height: 400px;
background-color: #888;
position: relative;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%)
}
方案三、通过margin计算上下边距设置垂直居中,然后用auto实现水平居中
.outer {
width: 400px;
height: 400px;
background-color: #888;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
margin: 150px auto;
}
方案四、类似方案二,设置上下左右距离都是0,然后设置auto的边距
.outer {
width: 400px;
height: 400px;
background-color: #888;
position: relative;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
方案五、类似方案三,先将子元素左上角定位到父元素中心,然后利用margin参考自身宽高,分别左移和上移50%
.outer {
width: 400px;
height: 400px;
background-color: #888;
position: relative;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)