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

如何在文本输入框左侧放置图片?

解决输入框左侧嵌入图片的问题

这里给你两种稳定的实现方式,都不会破坏现有布局:


方法1:利用input的background-image属性(最简洁)

这种方法不需要额外添加HTML元素,直接通过CSS给输入框设置背景图,调整内边距给图标留出空间即可,不会导致布局错乱。

修改你的CSS代码:

body {
  background-color: #141c2f;
  /* 让body占满视口高度,确保infoBox的垂直居中生效 */
  margin: 0;
  min-height: 100vh;
}

.search {
  background-color: #1d2c4c;
  border: none;
  border-radius: 10px;
  /* 移除文字居中,避免和左侧图标冲突 */
  padding-left: 45px; /* 给左侧图标预留空间,数值根据图标大小调整 */
  width: 500px;
  height: 50px;
  color: #fff; /* 适配深色背景的文字颜色 */
  /* 设置背景图:替换成你的图标路径,调整大小和位置 */
  background-image: url('你的搜索图标路径');
  background-size: 24px 24px;
  background-position: 12px center;
  background-repeat: no-repeat;
}

/* 去掉输入框聚焦时的默认边框 */
.search:focus {
  outline: none;
}

.infoBox {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

HTML保持原有结构即可。

你之前用background image没效果的原因

大概率是没设置background-position、background-size,或者没给输入框加padding-left,导致图标被输入文字覆盖,或是图片路径错误。


方法2:用Flex容器包裹图标和输入框(适合需要交互的图标)

如果你的图标需要点击交互,这种方式更灵活,通过外层容器把图标和输入框整合为视觉上的一个整体:

修改后的HTML:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./static/css/app.css">
  <title>Github User Search App</title>
</head>
<body>
  <div class="infoBox">
    <!-- 外层容器包裹图标和输入框 -->
    <div class="search-container">
      <img src="你的搜索图标路径" alt="搜索图标" class="search-icon">
      <input class="search" type="text" placeholder="Search..">
    </div>
  </div>
</body>
</html>

对应的CSS:

body {
  background-color: #141c2f;
  margin: 0;
  min-height: 100vh;
}

.search-container {
  background-color: #1d2c4c;
  border-radius: 10px;
  display: flex;
  align-items: center;
  padding: 0 12px;
}

.search-icon {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

.search {
  background-color: transparent; /* 输入框背景透明,继承容器背景 */
  border: none;
  width: 500px;
  height: 50px;
  color: #fff;
  outline: none;
}

.infoBox {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

这种方式通过flex布局让图标和输入框垂直居中,外层容器统一设置背景和圆角,输入框透明,视觉上完全是一个带图标的输入框,不会出现布局错乱问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:06:33