While there are many possible different methods for captioning an image, the solution I prefer in XHTML is to place the image in a definition list. This makes the most sense semantically – the image is the item we are defining, while the definition term is the caption – and is the most flexible in terms of markup. Note that the approach in HTML5 is very different, the latter language having markup explicitly designed for the purpose of captioning images.
A typical XHTML code example would be:
While this accomplishes our goal of a captioned image, it doesn’t look terribly good. First, let’s put a border on the definition list:
Note that this border makes it clear that our definition list takes up the entire horizontal space of our web page, which makes sense, as <dl> is a block tag. The height of the <dl> is determined by the content inside the list. Now let’s float it:
Note that when we float a block element it essentially collapses: now the width of our definition list is determined by the widest element it contains (the image).
We’ll add a little padding, margin-left and background-color; you could also remove the border at this stage:
The <dt> content is indented because that is the default for that element, just as it is for <li> elements, so let’s remove that with a separate style declaration:
At the same time, we’ll improve a few things about the caption:
Now the captioned image can have content wrapped around it. However, unlike an image by itself, it cannot be placed inside a paragraph:
While we have used this list to contain a single example, you could have multiple pairs of images and captions as definition terms and matching declarations in the same list.
Pro CSS3 Animation, Apress, 2013
Massive Head Canon
The New Defaults
CSSslidy