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
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.
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.
You "can" use same alt but you shouldn't! alt should always be a meaningful line describing what the image is.
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
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