144

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?

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • 4
    I wrote this (not fantastic) answer that's relevant: http://stackoverflow.com/questions/6949148/css-after-not-adding-content-to-certain-elements – thirtydot Sep 15 '11 at 00:26

3 Answers3

167

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.

Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
alex
  • 479,566
  • 201
  • 878
  • 984
11

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.

Joel Glovier
  • 7,469
  • 9
  • 51
  • 86
  • 7
    This seems correct, though the terminology has shifted since that HTML3 link (!). In HTML5, an img is what's called a "void" element. Examples of void elements include hr, input, and source. See: http://dev.w3.org/html5/markup/syntax.html#void-element // A quick bit of informal testing suggests that you can't add pseudo-elements to input elements either. – Ben Sep 13 '12 at 21:47
7

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

ASR
  • 1,801
  • 5
  • 25
  • 33
Ferdi Emmen
  • 275
  • 3
  • 10