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

如何为文本输入框添加图标且保持输入框背景色为白色

问题原因

你使用background简写属性设置背景图时,没有显式指定背景色,简写属性会默认将未声明的背景相关配置重置为初始值,其中背景色的初始值为透明,因此输入框原本的默认白色背景被覆盖,透出了页面的深灰色背景。

解决方法

有两种常用实现方案:

  • 方案1:在background简写属性中补充白色背景,同时调整背景图的位置、尺寸适配你的需求:
body{
    background-color: darkgrey;
}
input{
    /* 背景参数依次为:背景色、背景图、不重复、位置(距离左侧4px 垂直居中)、图标尺寸 */
    background: #fff url(https://i.sstatic.net/CGEmz.png) no-repeat left 4px center / 22px 22px;
    padding: 5px 5px 5px 30px;
}
  • 方案2:拆分background相关属性分别设置,避免简写覆盖默认属性:
body{
    background-color: darkgrey;
}
input{
    background-color: #fff;
    background-image: url(https://i.sstatic.net/CGEmz.png);
    background-repeat: no-repeat;
    background-position: left 4px center;
    background-size: 22px 22px;
    padding: 5px 5px 5px 30px;
}

额外说明:<input>属于单标签元素,不需要写</input>闭合标签,HTML代码可简化为<input type="email">。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:54:04