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

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

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


当前回答

问题提到“输入字段”。虽然我相信OP引用的是type=text、::after和::before的输入字段,但伪内容确实呈现了几种不同类型的输入字段:

input::before {
    content: "My content" /* 11 different input types will render this */
}    

这里是所有输入类型的全面演示,清楚地显示了哪些类型与(在本例中)::before伪元素兼容。

总之,这是可以呈现伪内容的所有输入类型的列表:

复选框颜色日期本地日期时间文件形象月无线电广播范围时间周

其他回答

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

<input type="checkbox" />

工作正常,与

<input type="radio" />

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

如果您试图使用: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>

总结

它不适用于<inputtype=“button”>,但适用于<输入type=“checkbox”>。

小提琴:http://jsfiddle.net/gb2wY/50/

HTML格式:

<p class="submit">
    <input id="submit-button" type="submit" value="Post">
    <br><br>
    <input id="submit-cb" type="checkbox" checked>
</p>

CSS:

#submit-button::before,
#submit-cb::before {
    content: ' ';
    background: transparent;
    border: 3px solid crimson;
    display: inline-block;
    width: 100%;
    height: 100%;
    padding: 0;
    margin: -3px -3px;
}

我使用背景图像为必填字段创建了红点。

input[type="text"][required] {
  background-image: radial-gradient(red 15%, transparent 16%);
  background-size: 1em 1em;
  background-position: top right;
  background-repeat: no-repeat
}

在Codepen上查看

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

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

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