147

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

3 Answers 3

170

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.

32
  • 25
    The real SOer should ask a question and 3 minutes after answer to himself, +1 ;-)
    – zerkms
    Sep 13, 2011 at 3:33
  • 57
    It's the future, still no specs... Nov 16, 2012 at 18:18
  • 22
    2017 here, same.
    – Hjalmar
    Feb 1, 2017 at 14:47
  • 30
    It's 2019, and 8 years passed. When will we reach the future exactly?
    – v3ntus
    Jan 16, 2019 at 15:56
  • 53
    Nearly 10 years later, many of us have gray hair and some have passed away. We have self-driving cars, but pseudo-elements on images is the one bit of technology that we can't figure out.
    – Kellen
    May 25, 2020 at 17:35
13

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.

1
  • 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: 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, 2012 at 21:47
8

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
  • Doesn't seem to work with Mac Firefox 17.
    – biziclop
    Jan 5, 2013 at 9:18
  • Only works for me in Firefox 23 if the image tag has a src that doesn't exist (404). Aug 13, 2013 at 1:55
  • 1
    I solved this by wrapping the img to span. Hackish, yes, but works in some occasions. Apr 16, 2015 at 11:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.