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

强颜欢笑 提交于 2019-11-26 01:53:55

问题


I am trying to use a :before pseudo element with an img element.

Consider this HTML and CSS...

HTML

<img src=\"http://0.gravatar.com/avatar/this-is-not-a-hash\" alt=\"\" />

CSS

img:before {
  content: \"hello\";
}

jsFiddle.

This does not produce the desired effect (tested in Chrome 13 and Firefox 6). However, it works with a div or span element.

Why not?

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


回答1:


The spec says...

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.

I guess this means they don't work with img elements (for now).

Also see this answer.




回答2:


Just for testing and knowing it's not pretty you can do the following to make the pseudo elements work with 'img' elements.

Add: display: block; content: ""; height: (height of image)px to the img element in your CSS.

Though it will render your img tag empty cause of the content: "" you can then

Add: style="background-image: url(image.jpg)" to your img element in html.

Tested this in Fx, Chrome and Safari




回答3:


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.



来源:https://stackoverflow.com/questions/7396469/why-dont-before-and-after-pseudo-elements-work-with-img-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!