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

如何在HTML与CSS中实现输入框(input)的垂直居中

问题描述

输入框未垂直居中的效果

我的目标是让图中的输入框(input)实现垂直居中,请问该如何实现?

现有代码如下:

CSS代码

.headmenu {
  background-color: rgb(47, 47, 47);
  width: auto;
  height: 30px;
}

.headmenu-right {
  float: right;
  padding-right: 15px;
}

.headmenu-right>input {
  border-radius: 15px;
  padding-left: 5px;
}

HTML代码

<div class="headmenu">
  <div class="headmenu-right">
    <input type="text">
  </div>
</div>

解决方案

要让输入框在导航栏中垂直居中,有几种简单可行的方法,下面分别说明:

方法1:利用行高与垂直对齐(适合固定高度容器)

给.headmenu-right设置line-height等于父容器.headmenu的高度(30px),同时给input添加vertical-align: middle属性,利用行高特性实现垂直居中:

.headmenu {
  background-color: rgb(47, 47, 47);
  width: auto;
  height: 30px;
}

.headmenu-right {
  float: right;
  padding-right: 15px;
  line-height: 30px; /* 行高匹配父容器高度 */
}

.headmenu-right>input {
  border-radius: 15px;
  padding-left: 5px;
  vertical-align: middle; /* 垂直对齐 */
}

方法2:Flex弹性布局(推荐,适配性更强)

放弃float布局,改用Flex来实现,这种方式不需要依赖固定高度,后续容器高度变化时也能自动保持居中:

.headmenu {
  background-color: rgb(47, 47, 47);
  width: auto;
  height: 30px;
  display: flex;
  justify-content: flex-end; /* 子元素靠右排列 */
  align-items: center; /* 垂直方向居中 */
}

.headmenu-right {
  padding-right: 15px;
}

.headmenu-right>input {
  border-radius: 15px;
  padding-left: 5px;
}

如果不需要额外的.headmenu-right容器,也可以简化HTML结构:

<div class="headmenu">
  <input type="text" style="padding-left:5px; border-radius:15px;">
</div>

方法3:定位+位移(适合复杂布局场景)

通过相对定位和绝对定位结合transform来实现居中,这种方式不受常规布局流的影响:

.headmenu {
  background-color: rgb(47, 47, 47);
  width: auto;
  height: 30px;
  position: relative; /* 父容器设为相对定位 */
}

.headmenu-right {
  position: absolute;
  right: 15px; /* 替代float和padding-right实现靠右 */
  height: 100%; /* 高度占满父容器 */
}

.headmenu-right>input {
  border-radius: 15px;
  padding-left: 5px;
  position: relative;
  top: 50%;
  transform: translateY(-50%); /* 向上位移自身高度的50%,实现垂直居中 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:15:45