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

CssPseudo ElementCss Content

Css Problem Overview


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?

Css Solutions


Solution 1 - Css

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.

Solution 2 - Css

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.

Solution 3 - Css

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexView Question on Stackoverflow
Solution 1 - CssalexView Answer on Stackoverflow
Solution 2 - CssJoel GlovierView Answer on Stackoverflow
Solution 3 - CssFerdi EmmenView Answer on Stackoverflow