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

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

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


当前回答

当我遇到同样的问题时,我发现了这篇文章,这是对我有效的解决方案。与替换输入的值相反,只需删除它并在其后面绝对放置一个大小相同的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>

其他回答

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

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

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

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

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

之后的API文档

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

您必须在输入周围使用某种包装器,才能使用before或after伪元素。这是一个fiddle,它在输入的包装器div上有一个before,然后将before放在输入内部-或者至少看起来像它。显然,这是一种变通方法,但在紧要关头很有效,并且有助于做出响应。如果你需要放一些其他内容,你可以很容易地让它成为一个after。

工作Fiddle

输入内的美元符号作为伪元素:http://jsfiddle.net/kapunahele/ose4r8uj/1/

HTML:

<div class="test">
    <input type="text"></input>
</div>

CSS:

input {
    margin: 3em;
    padding-left: 2em;
    padding-top: 1em;
    padding-bottom: 1em;
    width:20%; 
}


.test {
    position: relative;
    background-color: #dedede;
    display: inline;
}

.test:before {
    content: '$';
    position: absolute;
    top: 0;
    left: 40px;
    z-index: 1;
}

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

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>中。

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

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

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