如何为文本输入框添加图标且保持输入框背景色为白色
问题原因
你使用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
相关产品推荐
相关产品推荐

