Generated content is a powerful feature of CSS, though is not consistently supported in all browsers. Opera is surely among those browsers which have the most extended support to generated content. In fact, Opera allows generated content to be applied on images. This turns out to be very useful when we have to get particular effects with generated content. One of the most requested effects is to turn the alt
attribute of an image into an image caption. Let's say that we have an image gallery with the following styles:
#gallery { padding: 2em 0; } #gallery ul { margin: 0; padding: 0; list-style: none; overflow: hidden; } #gallery ul li { width: 30%; margin-right: 0.5em; float: left; height: 200px; } #gallery ul li img { display: block; width: 100%; height: 150px; }
To create image captions, just write this:
#gallery ul li img:after { content: attr(alt); display: block; text-align: center; font-style: italic; padding: 1em 0; }
And here's the result:
Unfortunately, this works only in the Opera browser.
Wouldn't it be better to use the title attribute rather than the alt attribute?
Nope. The title attribute forces assistive technologies to read another attribute instead of the alt attribute. title should be used very sparingly for such reason.