mo.notono.us

Wednesday, November 16, 2011

A non-trendy way to wrap text to the width of an image

Say you have an image, whose width is unknown.  You want to display a caption below the image, and the length of the caption text is also unknown.  How do you display the caption so that the text wraps to the width of the image?

As far as I know, there is no way to do this with divs and Css.  It *may* be possible to do it with figures and figcaptions, but now you’re in Html5 land, and to support older browsers you’ll need to do gymnastics.

You could use an img load event handler and resize the caption after the image comes in, but now you have to add javascript for something that should be handled by your html.

So you use tables.  Yes tables, those horrible, horrible remnants of Web 1.0.

And you do it like this (though your styles would obviously be in a css stylesheet somewhere):

<table>
<caption style="caption-side: bottom; margin: 0 5px;">Oh caption, my caption! our fearful task is done!<br>
The layout has weathered every wrack, the prize we sought is won</caption>
<tr><td><img alt="some unknown sized image" src="http://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Ocaptain.jpg/394px-Ocaptain.jpg">
&/lt;tr></table>

which renders thusly (Live writer may corrupt this - sorry view-sourcers):

Oh caption, my caption! our fearful task is done!
The layout has weathered every wrack, the prize we sought is won
some unknown sized image

Also see http://jsfiddle.net/austegard/fGwve/

Labels: , , ,