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

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

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


当前回答

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

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上查看

其他回答

这里有另一种方法(假设您可以控制HTML):在输入之后添加一个空的<span></span>,并在CSS中使用input.mystyle+span:after将其作为目标

.field包含错误{显示:内联;颜色:红色;}.field_with_errors输入+span:之后{内容:“*”}<div class=“field_with_errors”>标签:</div><div class=“field_with_errors”><input type=“text”/><span></span></div>

我在AngularJS中使用这种方法,因为它会自动将.ng无效类添加到<input>表单元素和表单中,但不会添加到<label>中。

总结

它不适用于<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)也称为“替换元素”,因为它们被替换为各自的内容。“外部对象”,因为缺少更好的术语。这里读得更好

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

<input type="checkbox" />

工作正常,与

<input type="radio" />

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