水平垂直居中的四种方式

html 布局结构如下

<div class="outerBox">
    <div class="innerBox"></div>
</div>

第一种 使用flex

.outerBox {
    height: 400px;
    background-color: rgb(12, 243, 232);
    display: flex;
    justify-content: center;
    align-items: center;
}

.innerBox {
    width: 200px;
    height: 200px;
    background-color: pink;
}

第二种 position + margin:auto

.outerBox {
    height: 400px;
    background-color: rgb(12, 243, 232);
    position: relative;
}

.innerBox {
    width: 200px;
    height: 200px;
    background-color: pink;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

第三种 position + margin负边距

.outerBox {
    height: 400px;
    background-color: rgb(12, 243, 232);
    position: relative;
}

.innerBox {
    width: 200px;
    height: 200px;
    background-color: pink;

    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
}

第四种 transform: translate

.outerBox {
    height: 400px;
    background-color: rgb(12, 243, 232);
    position: relative;
}

.innerBox {
    width: 200px;
    height: 200px;
    background-color: pink;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

posted @   南风晚来晚相识  阅读(160)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示