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

如何将搜索框在其.searchbar背景容器内垂直居中

你当前的布局下,align-self 仅在Flex/Grid布局中生效,vertical-align: middle 需要配合父元素行高设置或者display为table-cell才能生效,因此无法实现垂直居中。以下是三种可直接落地的实现方案:

方案1:Flex布局(推荐,兼容性好,代码简洁)

仅需要修改父容器.searchbar的display属性,新增两行Flex布局属性即可:

.searchbar {
  display: flex; /* 替换原来的display: block */
  width: 100%;
  height: 100px;
  overflow: hidden;
  background-color: lightgray;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  position: relative;
}
.searchbar input[type="text"] {
  color: black;
  text-align: left;
  text-decoration: none;
  width: 50%;
  height: 40px;
  font-size: 20px;
  /* 原有的align-self、position: relative、vertical-align都可以删除 */
}

方案2:绝对定位+位移(不需要修改父容器原有display属性)

父容器已经设置了position: relative,直接修改input的定位属性即可:

.searchbar input[type="text"] {
  color: black;
  text-align: left;
  text-decoration: none;
  width: 50%;
  height: 40px;
  font-size: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /* 原有的align-self、vertical-align可以删除 */
}

方案3:行高配合vertical-align

给父容器设置行高等于自身高度,input设置为行内块元素即可:

.searchbar {
  display: block;
  width: 100%;
  height: 100px;
  line-height: 100px; /* 新增,行高等于容器高度 */
  overflow: hidden;
  background-color: lightgray;
  text-align: center;
  position: relative;
}
.searchbar input[type="text"] {
  color: black;
  text-align: left;
  text-decoration: none;
  width: 50%;
  height: 40px;
  font-size: 20px;
  display: inline-block; /* 新增 */
  vertical-align: middle;
  /* 原有的align-self、position: relative可以删除 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:54:08