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

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

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


当前回答

总结

它不适用于<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;
}

其他回答

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

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

<input type="checkbox" />

工作正常,与

<input type="radio" />

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

:after和:before在Internet Explorer 7及以下版本中不受任何元素的支持。

它也不能用于替换的元素,如表单元素(输入)和图像元素。

换句话说,使用纯CSS是不可能的。

但是,如果使用jquery,则可以使用

$(".mystyle").after("add your smiley here");

之后的API文档

使用javascript附加内容。这将适用于所有浏览器。

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

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

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

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

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 }