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

如何将搜索图标对齐到搜索框内部 仅使用原生HTML/CSS实现

实现方案

核心采用父元素相对定位+图标绝对定位的原生CSS方案,无需引入任何第三方框架即可实现谷歌搜索栏同款效果。


修改后HTML代码

<form class="search-bar-form">
  <input id="search-bar" type="text" />
  <img class="search-icon" src="https://via.placeholder.com/24" alt="搜索图标" />
</form>

修改后CSS代码

/* 外层表单作为定位父级 */
.search-bar-form {
  position: relative;
  width: 32%;
}

#search-bar {
  /* 避免内边距撑宽输入框 */
  box-sizing: border-box;
  width: 100%;
  color: #fff;
  border-radius: 24px;
  border: 1px solid #fff;
  background-color: #2d2d2d;
  height: 44px;
  /* 左侧预留图标位置,数值可按需调整 */
  padding: 0 16px 0 52px;
}

/* 去掉输入框默认聚焦外边框,可按需自定义聚焦样式 */
#search-bar:focus {
  outline: none;
}

.search-icon {
  position: absolute;
  left: 16px;
  top: 50%;
  /* 实现图标垂直居中 */
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  /* 点击图标区域不拦截输入框焦点,匹配谷歌搜索栏交互逻辑 */
  pointer-events: none;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:57:03