CSS 为什么 :before 和 :after 伪元素不能与 `img` 元素一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7396469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why don't :before and :after pseudo elements work with `img` elements?
提问by alex
I am trying to use a :before
pseudo elementwith an img
element.
我正在尝试将:before
伪元素与元素一起使用img
。
Consider this HTML and CSS...
考虑这个 HTML 和 CSS ...
HTML
HTML
<img src="http://0.gravatar.com/avatar/this-is-not-a-hash" alt="" />
CSS
CSS
img:before {
content: "hello";
}
This does not produce the desired effect (tested in Chrome 13 and Firefox 6). However, it works with a div
or span
element.
这不会产生预期的效果(在 Chrome 13 和 Firefox 6 中测试)。但是,它适用于div
orspan
元素。
Why not?
为什么不?
Is there a way to make pseudo elements work with img
elements?
有没有办法让伪元素与img
元素一起工作?
回答by alex
规范说...
Note. This specification does not fully define the interaction of
:before
and:after
with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.
笔记。本规范没有完全定义替换元素(例如 HTML 中的 IMG)的交互
:before
和交互:after
。这将在未来的规范中更详细地定义。
I guess this means they don't work with img
elements (for now).
我想这意味着它们不适用于img
元素(目前)。
Also see this answer.
另请参阅此答案。
回答by Ferdi Emmen
Just for testing and knowing it's not pretty you can do the following to make the pseudo elements work with 'img' elements.
只是为了测试并知道它不漂亮,您可以执行以下操作以使伪元素与 'img' 元素一起使用。
Add: display: block; content: ""; height: (height of image)px
to the img element in your CSS.
添加:display: block; content: ""; height: (height of image)px
到您的 CSS 中的 img 元素。
Though it will render your img tag empty cause of the content: ""
you can then
虽然它会使您的 img 标签变为空,但content: ""
您可以
Add: style="background-image: url(image.jpg)"
to your img element in html.
style="background-image: url(image.jpg)"
在 html 中添加:到您的 img 元素。
Tested this in Fx, Chrome and Safari
在 Fx、Chrome 和 Safari 中对此进行了测试
回答by Joel Glovier
It could be that browser vendors have not implemented pseudo elements on the img
tag because of their interpretation of the spec: the img
element, strictly speaking, is not a block level element or an inline element, it is an empty element.
可能是浏览器供应商没有在img
标签上实现伪元素,因为他们对规范的解释:img
元素,严格来说,不是块级元素或内联元素,它是一个空元素。