如何在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">☎ 052 824 134</div> <div class="adres">✯ бул. Княз Борис 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
相关产品推荐
相关产品推荐

