8

I've tried this and it works fine

<p alt="world">hello</p>

With CSS

p::after {
  content: attr(alt);
}

But it doesn't work when I try

<img src="http://placehold.it/300x300" alt="my image caption">

With CSS

img::after {
  content: attr(alt);
}

Is it possible to output alt text for an img using CSS?

Please indicate browser compatibility with any solution you provide.

Here's a jsfiddle

Mulan
  • 129,518
  • 31
  • 228
  • 259
  • not using CSS alone, you can using JS or jQuery. – Amir5000 Apr 20 '14 at 23:33
  • `alt` attribute is only valid HTML on `img`, `input[type="image"]` and `area` elements (and object[type="image"] but that's anecdotal). It's also mandatory (and can have an empty value like `alt=""` in some contexts) – FelipeAls Apr 21 '14 at 09:10

1 Answers1

10

This is by design.

img tags are self-closing (<tag />) tag, and therefore they contain no "content". Since they do not contain any content, no content can be appended (i.e. ::after) or prepended (i.e. ::before).

This is also the case for other self-closing HTML elements:

<area>, <base>, <br>, <col>, <command>, <embed>, <hr>, <keygen>, <link>, <meta>, <param>, <source>, <track> and <wbr>

Here's what the (CSS2) 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. [2014: hasn't happened yet]

Source: http://www.w3.org/TR/CSS2/generate.html#before-after-content

adaam
  • 3,700
  • 7
  • 27
  • 51
  • 3
    Yup. `:after` is actually `:end-of-innerHTML`. `:before` is actually `:start-of-innerHTML`. And self-closing tags don't have innerHTML. – bjb568 Apr 20 '14 at 23:32
  • 1
    How disappointing. There's no way around this then? – Mulan Apr 20 '14 at 23:33
  • 4
    @naomik Beg the spec writers to make the spec suck less. Then expect IE support in 2100. – bjb568 Apr 20 '14 at 23:35
  • 1
    there is another question about it: http://stackoverflow.com/questions/5843035/does-before-not-work-on-img-tags – Yaron U. Apr 20 '14 at 23:36