我试图在输入字段上使用: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">

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

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


当前回答

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

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

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

其他回答

奇怪的是,它可以处理某些类型的输入。至少在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>

如果您试图使用:before和:after来设置输入元素的样式,那么很可能您试图模仿CSS堆栈中其他span、div甚至某个元素的效果。

正如Robert Koritnik的回答所指出的,:before和:after只能应用于容器元素,而输入元素不是容器。

然而,HTML5引入了button元素,它是一个容器,其行为类似于input[type=“submit | reset”]元素。

    <style>
    .happy:after { content:url(smiley.gif); }
    </style>

    <form>
    <!-- won't work -->
    <input class="happy" type="submit" value="Submit" />

    <!-- works -->
    <button class="happy">Submit</button>
    </form>

下一步尝试:

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

伪元素如:after、:before仅用于容器元素。在单个位置开始和结束的元素,如<input/>、<img>等,都不是容器元素,因此不支持伪元素。一旦将伪元素应用于容器元素(如<div>),如果检查代码(参见图片),就可以理解我的意思。实际上,伪元素是在容器元素内部创建的。这在<input>或<img>的情况下是不可能的