html - 我可以使用 :before or :after pseudo-element on a

我正在尝试在 input 字段上使用 :after CSS 伪元素,但它不起作用。如果我将它与 span 一起使用,它可以正常工作。

<style type="text/css">
.mystyle:after {content:url(smiley.gif);}
.mystyle {color:red;}
</style>

这行得通(将笑脸放在“buu!”之后和“更多”之前)

<span class="mystyle">buuu!</span>a some more

这不起作用 - 它只会将 someValue 涂成红色,但没有笑脸。

<input class="mystyle" type="text" value="someValue">

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

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

最佳答案

:before:after 在容器内渲染

和<input>不能包含其他元素。


伪元素只能在容器元素上定义(或者说只支持)。因为它们的呈现方式是 within 容器本身作为子元素。 input 不能包含其他元素,因此它们不受支持。另一方面,一个 button 也是一个表单元素支持它们,因为它是其他子元素的容器。

如果你问我,如果某些浏览器确实在非容器元素上显示这两个伪元素,这是一个错误和非标准一致性。规范直接讲元素内容...

W3C 规范

如果我们仔细阅读 the specification它实际上是说它们被插入 inside 一个包含元素:

Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.

看到了吗? 元素的文档树内容。据我了解,这意味着容器中。

关于html - 我可以使用 :before or :after pseudo-element on an input field?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2587669/

相关文章:

javascript - 如何在页面加载后执行 JavaScript?

html - 如何使 "position: absolute"元素居中

javascript - 从父页面调用 iframe 中的 JavaScript 代码

html - 名称为 ='' 的无效表单控件不可聚焦

html - 确定用户的时区

html - CSS 背景不透明度

html - 禁用 Chrome 自动填充

c# - 如何使用 HTML 敏捷包

javascript - 如何播放音频?

javascript - 使用 jQuery 获取元素的类列表