Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 680
alex Avatar asked Oct 05 '22 19:10

alex


People also ask

Can I have multiple before pseudo elements for the same element?

In CSS2. 1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

What does the pseudo selectors allows us to do before and after?

CSS ::before and ::after pseudo-elements allow you to insert “content” before and after any non-replaced element (e.g. they work on a <div> but not an <input> ). This effectively allows you to show something on a web page that might not be present in the HTML content.

Can pseudo elements and pseudo-classes be combined?

There are no special rules around combining pseudo-classes and pseudo-elements, besides the one rule that says there can only be one pseudo-element per complex selector and it must appear at the very end.

Can I use pseudo elements on IMG?

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. Add: style="background-image: url(image. jpg)" to your img element in html.


2 Answers

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.

like image 156
alex Avatar answered Oct 19 '22 11:10

alex


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.

like image 8
Joel Glovier Avatar answered Oct 19 '22 10:10

Joel Glovier