I am trying to use a :before
pseudo element with an img
element.
Consider this HTML and CSS...
<img src="http://0.gravatar.com/avatar/this-is-not-a-hash" alt="" />
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?
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.)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With