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

如何使用CSS和HTML实现文本在边框容器中居中对齐

导航栏带红边框容器内文本居中解决方案

针对你遇到的问题,用flex或grid布局都能轻松实现文本居中,以下是具体修改方法:

方法一:Flex布局

给带左右红边框的容器添加flex相关样式,通过justify-content和align-items实现水平+垂直居中:

/* 替换成你实际使用的红边框容器类名 */
.has-red-border {
  border-left: 2px solid red;
  border-right: 2px solid red;
  display: flex;
  justify-content: center; /* 水平居中文本 */
  align-items: center; /* 垂直居中文本 */
  height: 100%; /* 继承导航栏高度,确保垂直居中生效 */
}

如果导航栏没有设置固定高度,也可以给容器添加padding来保证文本垂直方向的间距,替代height:100%。

方法二:Grid布局

用grid的place-items属性可以一步实现双方向居中,代码更简洁:

/* 替换成你实际使用的红边框容器类名 */
.has-red-border {
  border-left: 2px solid red;
  border-right: 2px solid red;
  display: grid;
  place-items: center; /* 同时实现水平和垂直居中 */
  height: 100%; /* 继承导航栏高度,适配垂直居中 */
}

额外提示:如果导航栏父元素设置了display: flex,可以给红边框容器加flex: 1,让它占据对应宽度,避免容器仅包裹文本导致红边框过窄。

内容的提问来源于stack exchange,提问作者Duong Duc Dung FX22797

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:07:07