gin49sz

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

元素水平垂直居中方法

方案一、弹性盒子沿主轴和侧轴居中

.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;
}
posted on   树深时见鹿nnn  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
 
点击右上角即可分享
微信分享提示