Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display img alt text using CSS? [duplicate]

Tags:

css

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

like image 978
Mulan Avatar asked Apr 20 '14 23:04

Mulan


People also ask

How do I add alt text to an image in CSS?

If you use an image purely for design purposes, embed the image in the CSS file, not the HTML file. However, if the image is in the HTML file, leave the alt attribute empty like so, alt=“”. This ensures that the screen reader skips such an image.

How do I show alt text on an image?

To add alt text to a picture, shape, chart, or SmartArt graphic, right-click on the object and choose Format Picture. In the Format Picture panel, choose the Layout and Properties icon. Then choose Alt Text.

Can two images have the same alt text?

You "can" use same alt but you shouldn't! alt should always be a meaningful line describing what the image is.


1 Answers

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

like image 53
adaam Avatar answered Oct 15 '22 02:10

adaam