Does :before not work on img elements?

Joshua Frank picture Joshua Frank · Apr 30, 2011 · Viewed 238k times · Source

I'm trying to use the :before selector to place an image over another image, but I'm finding that it simply doesn't work to place an image before an img element, only some other element. Specifically, my styles are:

.container
{
   position: relative;
   display: block;
}

.overlay:before
{
    content: url(images/[someimage].png);
    position: absolute;
    left:-20px;
    top: -20px;
}

and I find that this works fine:

<a href="[url]" class="container">
  <span class="overlay"/>
  <img width="200" src="[url]"/>
</a>

but this does not:

<a href="[url]" class="container">
  <img width="200" src="[url]" class="overlay"/>
</a>

I can use a div or p element instead of that span, and the browser correctly overlays my image over the image in the img element, but if I apply the overlay class to the img itself, it doesn't work.

I'd like to get this working because that extra span offends me, but more importantly, I've got about 100 blog posts that I'd like to modify, and I can do this in one go if I could just modify the stylesheet, but if I have to go back and add an extra span element in between the a and img elements, this will be a lot more work.

Answer

cwharris picture cwharris · Apr 30, 2011

Unfortunately, most browsers do not support using :after or :before on img tags.

http://lildude.co.uk/after-css-property-for-img-tag

However, it IS possible for you to accomplish what you need with JavaScript/jQuery. Check out this fiddle:

http://jsfiddle.net/xixonia/ahnGT/

$(function() {

    $('.target').after('<img src="..." />');

});

Edit:

For the reason why this isn't supported, check out coreyward's answer.