You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置使父容器内的子div实现水平与垂直居中?

解决方案:Flex布局实现子元素水平垂直居中

我正在制作一款测试类界面,需要让.top_header容器内的三个子div(.top_header_logo、.top_header_product、.top_header_manual)在父容器内实现水平与垂直居中。尝试过text-align和flex布局,但未得到理想效果。

原HTML代码

<body>
    <div class="top_header">
        <div class="top_header_logo">test</div>
        <div class="top_header_product">test</div>
        <div class="top_header_manual">test</div>
</body>

原CSS代码

body {
    margin: 0px auto;
    padding: 0px;
}

.top_header {
    border: 1px solid gainsboro;
    height: 70px;
    display: flex;
    align-items: center;
}

.top_header_logo {
    border: 1px solid blue;
    float: left;
    width: 20%;
    height: 70px;
    box-sizing: border-box;
    text-align: center;
    /* margin-top: 20px; */
    font-family: 'Bungee', sans-serif;
    font-size: 20px;
}

.top_header_product {
    border: 1px solid red;
    float: left;
    width: 20%;
    height: 70px;
    box-sizing: border-box;
    text-align :center;
    margin-top: 20px;
    font-family: 'Bungee', sans-serif;
    font-size: 20px;
}

.top_header_product:hover {
    color: cornflowerblue;
}

.top_header_manual {
    float: left;
    width: 20%;
    height: 70px;
    box-sizing: border-box;
    text-align: center;
    margin-top: 20px;
    font-family: 'Bungee', sans-serif;
    font-size: 20px;
}

.top_header_empty {
    width: 17%;
    float: left;
    height: 70px;    
}

修正方案

问题根源

父容器已设置display: flex和align-items: center,但子元素的float: left、height: 70px、margin-top属性会干扰flex布局生效,同时父容器缺少水平居中的flex属性设置。

修正步骤

  1. 移除所有子元素的float: left、height: 70px、margin-top属性
  2. 给父容器.top_header添加justify-content: center实现水平居中
  3. 子元素的垂直居中由父容器的align-items: center自动实现,保留width: 20%维持宽度

修正后的CSS代码

body {
    margin: 0px auto;
    padding: 0px;
}

.top_header {
    border: 1px solid gainsboro;
    height: 70px;
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
}

.top_header_logo {
    border: 1px solid blue;
    width: 20%;
    box-sizing: border-box;
    text-align: center;
    font-family: 'Bungee', sans-serif;
    font-size: 20px;
}

.top_header_product {
    border: 1px solid red;
    width: 20%;
    box-sizing: border-box;
    text-align: center;
    font-family: 'Bungee', sans-serif;
    font-size: 20px;
}

.top_header_product:hover {
    color: cornflowerblue;
}

.top_header_manual {
    width: 20%;
    box-sizing: border-box;
    text-align: center;
    font-family: 'Bungee', sans-serif;
    font-size: 20px;
}

/* .top_header_empty 未在HTML中出现,可按需保留或删除 */
.top_header_empty {
    width: 17%;
    height: 70px;    
}

可选调整

如果需要三个子元素在容器内均匀分布(而非挤在一起居中),可将父容器的justify-content: center替换为justify-content: space-around或justify-content: space-between,根据布局需求选择。

内容的提问来源于stack exchange,提问作者Yong Han

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 18:45:11