我试图在输入字段上使用:after CSS伪元素,但它不起作用。如果我将其与跨度一起使用,它可以正常工作。

<style type="text/css">
.mystyle:after {content:url(smiley.gif);}
.mystyle {color:red;}
</style>

这是有效的(将笑脸放在“buu!”之后,然后放在“somemore”之前)

<span class="mystyle">buuu!</span>a some more

这不起作用-它只将someValue涂成红色,但没有笑脸。

<input class="mystyle" type="text" value="someValue">

我做错了什么?我应该使用另一个伪选择器吗?

注意:我不能在输入周围添加跨度,因为它是由第三方控件生成的。


当前回答

下一步尝试:

label[for=“userName”]{位置:相对;}label[for=“userName”]::之后{content:'[after]';宽度:22px;高度:22px;显示:内联块;位置:绝对;右:-30像素;}<label for=“userName”>姓名:<input type=“text”name=“userName”id=“userName“></label>

其他回答

奇怪的是,它可以处理某些类型的输入。至少在Chrome中,

<input type="checkbox" />

工作正常,与

<input type="radio" />

只是type=text和其他一些不起作用。

当我遇到同样的问题时,我发现了这篇文章,这是对我有效的解决方案。与替换输入的值相反,只需删除它并在其后面绝对放置一个大小相同的span,span可以使用您选择的图标字体将:before伪类应用于它。

<style type="text/css">

form {position: relative; }
.mystyle:before {content:url(smiley.gif); width: 30px; height: 30px; position: absolute; }
.mystyle {color:red; width: 30px; height: 30px; z-index: 1; position: absolute; }
</style>

<form>
<input class="mystyle" type="text" value=""><span class="mystyle"></span>
</form>

您不能在输入元素中放置伪元素,但可以放置阴影元素,如占位符!

input[type="text"] {   
  &::-webkit-input-placeholder {
    &:before {
      // your code
    }
  }
}

要使其在其他浏览器中工作,请在不同的选择器中使用:-moz占位符、::-moz placeholder和:-ms input placeholder。无法对选择器进行分组,因为如果浏览器无法识别选择器,则整个语句将无效。

更新:以上代码仅适用于CSS预处理器(SASS、LESS…),不使用预处理器:

input[type="text"]::-webkit-input-placeholder:before { // your code }

:before和:after仅适用于可以具有子节点的节点,因为它们将新节点作为第一个或最后一个节点插入。

:before和:after应用于容器内部,这意味着您可以将其用于带有结束标记的元素。

它不适用于自动关闭元件。

另一方面,自动关闭的元素(如img/hr/input)也称为“替换元素”,因为它们被替换为各自的内容。“外部对象”,因为缺少更好的术语。这里读得更好