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

如何在div容器内实现文本水平居中?附现有代码求助

解决方案

核心修改点

  • 给父容器.header添加Flex布局,实现内部元素的水平+垂直居中
  • 移除.phone中强制偏移的左内边距
  • 调整子元素间距,优化布局合理性

修改后的代码

CSS

.header{
    background: #ff6400;
    height:40px;
    box-sizing: border-box;
    margin: 0 auto;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    gap: 20px; /* 子元素间距,可按需调整 */
}
.phone{
    color: white; 
    font-size: 20px; 
}
.adres{
    color: white; 
    font-size: 20px;
}

HTML(结构无需改动)

<div class="header">
    <div class="phone">&#9742; 052 824 134</div>
    <div class="adres">&#10031; бул. Княз Борис I, No 115 - Дворец на Културата и Спорта</div>
</div>

兼容旧浏览器的方案

如果需要适配不支持Flex的环境,可改用以下方案:

.header{
    background: #ff6400;
    height:40px;
    box-sizing: border-box;
    margin: 0 auto;
    text-align: center; /* 让inline-block子元素水平居中 */
    line-height: 40px; /* 通过行高实现垂直居中 */
}
.phone{
    color: white; 
    font-size: 20px; 
    display: inline-block;
    margin-right: 20px; /* 设置子元素间距 */
}
.adres{
    color: white; 
    font-size: 20px;
    display: inline-block;
}

内容的提问来源于stack exchange,提问作者Kristiyan Rusev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:01:10