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

为何Input元素使用带SVG的CSS ::after伪元素无效?

问题根源

<input>属于替换元素,这类元素的内容由浏览器外部资源或原生控件渲染(比如文本输入框的输入区域),CSS的::before/::after伪元素无法在替换元素上生成额外内容,这是你代码失效的核心原因。

修复方案

提供两种实用的替代方法:

方法1:利用父容器添加伪元素

给<input>套一个父容器,将伪元素绑定到父容器上,通过定位实现图标效果:

修改后的HTML

<div class="section">
  <div class="input-wrapper">
    <input type="text" name="location" id="location" placeholder="United State">
  </div>
  <button type="button" class="search-button">🔍</button>
</div>

对应CSS

.section .input-wrapper {
  position: relative;
  display: inline-block; /* 适配input的宽度 */
}
.section .input-wrapper::after {
  content: '';
  display: inline-block;
  position: absolute;
  background-image:url('#{$svgPath}pin.svg') ;
  width: 16px;
  height: 20px;
  top: 50%;
  left: 10px;
  transform: translateY(-50%); /* 精准垂直居中 */
  background-size: contain;
  background-repeat: no-repeat;
  pointer-events: none; /* 避免图标遮挡input的点击/输入操作 */
}
.section #location {
  padding-left: 36px; /* 给图标预留空间,防止文字覆盖 */
}

方法2:直接将图标作为input的背景图

如果不需要伪元素的额外特性,直接用background属性实现更简洁:

修改后的CSS

.section #location {
  padding-left: 36px;
  background-image:url('#{$svgPath}pin.svg') ;
  background-size: 16px 20px;
  background-repeat: no-repeat;
  background-position: 10px center; /* 水平10px,垂直居中 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 00:58:24