Orbeon Forms教程:如何为文本字段添加图标
给文本输入框左侧添加图标的解决方案
你遇到的问题是因为<input>属于替换元素,绝大多数浏览器不支持直接给它添加:before/:after伪元素,所以得换个思路,下面给你两种实用的实现方式:
方法1:用容器包裹图标与输入框
直接用一个容器把图标和输入框放在一起,通过定位让图标固定在输入框左侧:
HTML代码
<!-- 邮箱输入框示例 --> <div class="input-container"> <span class="input-icon">📧</span> <input type="email" class="form-input" placeholder="请输入邮箱地址"> </div> <!-- 电话号码输入框示例 --> <div class="input-container"> <span class="input-icon">📞</span> <input type="tel" class="form-input" placeholder="请输入电话号码"> </div>
CSS代码
.input-container { position: relative; display: inline-block; margin: 10px 0; } .input-icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-size: 18px; color: #888; } .form-input { padding-left: 40px; /* 给图标留出足够空间 */ padding-right: 15px; height: 40px; border: 1px solid #ddd; border-radius: 6px; font-size: 16px; } .form-input:focus { outline: none; border-color: #409eff; }
方法2:利用父容器的伪元素实现
如果不想额外加图标标签,可以给输入框的父容器添加:before伪元素来充当图标:
HTML代码
<div class="email-input-wrap"> <input type="email" placeholder="请输入邮箱地址"> </div> <div class="phone-input-wrap"> <input type="tel" placeholder="请输入电话号码"> </div>
CSS代码
.email-input-wrap, .phone-input-wrap { position: relative; display: inline-block; margin: 10px 0; } /* 邮箱图标 */ .email-input-wrap:before { content: "📧"; position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-size: 18px; color: #888; } /* 电话图标 */ .phone-input-wrap:before { content: "📞"; position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-size: 18px; color: #888; } .email-input-wrap input, .phone-input-wrap input { padding-left: 40px; padding-right: 15px; height: 40px; border: 1px solid #ddd; border-radius: 6px; font-size: 16px; } .email-input-wrap input:focus, .phone-input-wrap input:focus { outline: none; border-color: #409eff; }
补充说明
如果想用专业的图标字体,只需要把content的值换成对应图标的编码(比如Font Awesome的邮箱图标编码是\f0e0),同时确保你已经引入了对应的图标字体文件即可。
内容的提问来源于stack exchange,提问作者Pete Atkin
相关产品推荐
相关产品推荐

