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

如何让三个同高元素水平对齐并使<b>标签文本垂直居中?

问题:实现三个元素水平对齐及<b>标签文本垂直居中

我有三个高度相同的元素(两个按钮和一个<b>标签),希望它们能水平对齐显示,同时让<b>标签内的文本垂直居中。当前显示效果不符合预期,请问如何实现?

HTML/React代码:

<div className="ContainerDiv">
  <button className="MinusButton"></button>
  <b className="Counter">100</b>
  <button className="PlusButton"></button>
</div>

原CSS代码:

.PlusButton {
  background-color: blue;
  width: 100px;
  height: 100px;
  display: inline-block;
}

.Counter {
  display: inline-block;
  background-color: white;
  width: 200px;
  height: 100px;
  text-align: center;
  color: #282c34;
  display: inline-block;
}

.MinusButton {
  background-color: blue;
  width: 100px;
  height: 100px;
  display: inline-block;
}

.ContainerDiv {
  display: inline-block;
  vertical-align: center;
  text-align: center;
}

解决方案

方案1:使用Flexbox(推荐,更简洁稳定)

Flexbox是现代布局方案,能轻松实现元素对齐,无需处理inline-block的间隙问题:

  1. 修改容器的CSS:
.ContainerDiv {
  display: flex; /* 切换为flex布局 */
  align-items: center; /* 让子元素垂直居中对齐 */
}
  1. 给<b>标签添加文本垂直居中样式:
.Counter {
  display: inline-block;
  background-color: white;
  width: 200px;
  height: 100px;
  text-align: center;
  color: #282c34;
  /* 新增文本垂直居中代码 */
  display: flex;
  align-items: center; /* 垂直方向居中 */
  justify-content: center; /* 水平方向居中(与text-align:center效果一致,可选) */
}

修改后,三个元素会自动水平排列,整体垂直对齐,<b>标签内的文本也会在盒子里完全居中。


方案2:修正inline-block布局的问题

如果坚持使用inline-block布局,需要解决两个核心问题:元素对齐和文本垂直居中:

  1. 修复元素水平对齐的间隙与垂直对齐:
.ContainerDiv {
  display: inline-block;
  font-size: 0; /* 消除inline-block元素之间的默认间隙 */
}

/* 给三个子元素统一设置垂直对齐,同时恢复字体大小 */
.MinusButton, .PlusButton, .Counter {
  vertical-align: middle; /* 让元素垂直对齐 */
  font-size: 16px; /* 恢复默认字体大小,避免文本消失 */
}
  1. 给<b>标签添加文本垂直居中:
.Counter {
  display: inline-block;
  background-color: white;
  width: 200px;
  height: 100px;
  text-align: center;
  color: #282c34;
  line-height: 100px; /* 行高等于元素高度,实现单行文本垂直居中 */
}

原代码的问题说明

  • vertical-align: center是无效值,CSS中没有这个属性值,正确的垂直对齐值为middle、top、bottom等。
  • 容器的vertical-align属性作用于容器本身和外部元素的对齐,不会影响容器内部子元素的排列。
  • 原代码仅给<b>标签设置了水平居中text-align: center,未处理垂直方向的文本居中。

内容的提问来源于stack exchange,提问作者Mr. Man

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 05:26:13