【问题标题】:Vertically center both Icon and span in a div [duplicate]在 div 中将 Icon 和 span 垂直居中 [重复]
【发布时间】:2026-02-23 04:55:02
【问题描述】:

结构是这样的:

css
.toolBarHolder {
  height: 42px;
  line-height: 42px;
}
<div class='toolBarHolder'>
  <icon class='toolBarIcon'>near_me</icon>
  <span class='toolBarText'>lake area</span>
</div>

这样span 可以垂直居中,但icon 失败。

【问题讨论】:

  • 错误说明了什么?
  • @xmastertje 我刚刚添加了一张照片
  • 你可以试试.toolBarIcon { vertical-align: middle; }

标签: html css


【解决方案1】:

只需将属性display:flex; align-items:center; justify-content:center; 赋予.toolBarHolder。不需要使用 line-height;

应该是这样的:

css
.toolBarHolder {
  height: 42px;
  display:flex;
  align-items:center;
  justify-content:center;
}

P.D.:由于我们使用的是justify-content: center,因此您还必须设置宽度(div 内容也水平居中)。

【讨论】:

  • 如果想要文字上方的图标,加flex-direction:column;@MotokoNanano