18

Is it possible to append text to images using the ::after pseudo-selector?

img[src="images/interface-zoom-buttons.png"]::after {
    content: "these are the zoom buttons";
}

The desire is to use the selector to provide a caption (other styling will be applied to the content of the selector) for images that get used over and over again in multiple HTML documents.

In the above example the image appears correctly and you can see that the appropriate CSS has been applied, but the content (supplied by the selector) is not seen in the output.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • Thanks for the heads up on the dupe @JukkaKKorpela. I had searched for one, but had limited my search to the image tag and did not see this one come up in the suggested list of dupes. – Jay Blanchard Oct 15 '14 at 12:20

1 Answers1

29

An img tag can not have child elements. Because img is a void element and its content model never allows it to have contents under any circumstances.

::after creates a pseudo element as the last child of its parent.

So img::after will not work ultimately because the browser will not allow it based on definition.

What you can do is to contain the img in a container and have ::after on the container.

Demo http://jsfiddle.net/x2za91jw/

HTML

<div class="container">
    <img src="http://www.gazette-ariegeoise.fr/IMG/jpg/test.jpg" />
</div>

CSS

.container {
    position: relative;
}
.container::after {
    position: absolute;
    top: 0;
    left: 0;
    border: 1px solid #000;
    content:"these are the zoom buttons";
}
Arbel
  • 30,599
  • 2
  • 28
  • 29
  • 1
    HTML content models do not restrict what you can do in CSS. Browsers do. – Jukka K. Korpela Oct 15 '14 at 05:43
  • Thank you for the answer @Arbel. I was aware that I could after on the container I just couldn't find anything about images. I was hoping not to have to do some JavaScript trickery but I'm guessing that will be my only solution in this case. – Jay Blanchard Oct 15 '14 at 12:19
  • @JukkaK.Korpela Thanks I rephrased the sentence to be more clear. – Arbel Oct 15 '14 at 15:53
  • @JayBlanchard You are welcome! Glad to be of help to you. – Arbel Oct 15 '14 at 15:54