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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:35:41  来源:igfitidea点击:

Why don't :before and :after pseudo elements work with `img` elements?

csspseudo-elementcss-content

提问by alex

I am trying to use a :beforepseudo elementwith an imgelement.

我正在尝试将: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";
}

jsFiddle.

js小提琴

This does not produce the desired effect (tested in Chrome 13 and Firefox 6). However, it works with a divor spanelement.

这不会产生预期的效果(在 Chrome 13 和 Firefox 6 中测试)。但是,它适用于divorspan元素。

Why not?

为什么不?

Is there a way to make pseudo elements work with imgelements?

有没有办法让伪元素与img元素一起工作?

回答by alex

The spec says...

规范说...

Note. This specification does not fully define the interaction of :beforeand :afterwith 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 imgelements (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)pxto 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 imgtag because of their interpretation of the spec: the imgelement, strictly speaking, is not a block level element or an inline element, it is an empty element.

可能是浏览器供应商没有在img标签上实现伪元素,因为他们对规范的解释:img元素,严格来说,不是块级元素或内联元素,它是一个空元素