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

Chrome浏览器中input的placeholder与光标无法垂直居中的解决方法

问题:Chrome中Input输入框Placeholder和光标无法垂直居中

我遇到一个问题:input输入框的placeholder和光标无法垂直居中,该问题仅出现在Chrome浏览器中,在Firefox中显示正常。请问如何解决该问题,确保在不同浏览器中都能实现一致的垂直对齐效果?

HTML代码

<input
  type="text"
  placeholder="Search term label"
  className={cx('search-header__input')}
/>

CSS代码

.search-header__input {
  border: none;
  width: 80%;
  height: rem(24px);

  &:focus {
    outline: none;
  }
}

问题展示

问题截图


解决方案

这个问题源于Chrome和Firefox对input元素默认排版规则的差异,直接设置固定height时,Chrome不会自动处理内部内容的垂直居中。以下是几种可靠的解决方法:

1. 用line-height替代固定height(推荐)

移除固定height,改用line-height控制输入框高度,搭配min-height保证最低尺寸,浏览器会自动完成垂直居中:

.search-header__input {
  border: none;
  width: 80%;
  line-height: rem(24px);
  min-height: rem(24px);
  padding: 0; /* 清除默认内边距避免干扰 */

  &:focus {
    outline: none;
  }
}

2. 结合padding与box-sizing调整

若必须保留固定height,可通过上下padding均分剩余空间,并开启box-sizing: border-box确保尺寸计算准确:

.search-header__input {
  border: none;
  width: 80%;
  height: rem(24px);
  box-sizing: border-box;
  padding: rem(4px) 0; /* 上下内边距均分,实现内容居中 */

  &:focus {
    outline: none;
  }
}

3. 强制统一垂直对齐样式

添加vertical-align: middle强制垂直对齐,同时重置input的默认内外边距:

.search-header__input {
  border: none;
  width: 80%;
  height: rem(24px);
  vertical-align: middle;
  margin: 0;
  padding: 0;

  &:focus {
    outline: none;
  }
}

以上方法均可解决Chrome中的垂直居中问题,同时保证Firefox显示效果一致,优先推荐第一种方案,更适配现代CSS排版逻辑,减少固定高度带来的适配风险。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:14:59