求助:input的:before伪元素使用FontAwesome无效,该排查什么?
问题解答:Input元素无法显示:before伪元素的FontAwesome图标
嘿,这个坑很多人都踩过!你遇到的问题核心原因是:input属于「替换元素」,浏览器不允许给这类元素添加:before/:after伪元素。
替换元素(比如input、img、select、textarea这些)的内容是由浏览器负责渲染的外部/原生内容,CSS的伪元素机制无法作用在它们身上——这就是为什么你的:focus样式正常生效,但:before完全没反应的原因。
解决方案:用父容器包裹Input,给容器加伪元素
最简单的办法是给input套一个父容器,把:before伪元素加在容器上,再通过定位让图标看起来像是在输入框内部。
修改后的代码示例:
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"> <div class="input-wrapper"> <input type="text" class="font-awesome" /> </div>
.input-wrapper { position: relative; /* 为伪元素定位做准备 */ display: inline-block; /* 避免容器占满整行 */ } .font-awesome { border-radius: 15px; border: 1px solid gray; padding: 0 15px 0 30px; /* 左边留足够空间给图标 */ line-height: 30px; outline: none; } .font-awesome:focus { border-color: lightblue; } /* 把伪元素加在父容器上 */ .input-wrapper:before { font-family: FontAwesome; content: "\f002"; position: absolute; left: 10px; /* 调整图标和输入框左边的距离 */ top: 50%; transform: translateY(-50%); /* 垂直居中 */ color: gray; /* 可以给图标加个颜色,和输入框风格统一 */ }
这样调整后,放大镜图标就能正常显示在输入框左侧,同时:focus的样式也能保持正常工作啦~
内容的提问来源于stack exchange,提问作者isexxx
相关产品推荐
相关产品推荐

