This article describes a CSS-based solution for creating a floated <figure> element that allows for a caption (<figcaption>) to be displayed beneath – constrained to the width of the image.
The example on the left is a fairly common design element, yet one that can be a bit of a pain to style if you want to keep things as fluid and flexible as possible.
The solution I came up with is based on a Stack Overflow posting I read that has been modified to work on a wider range of browsers – including IE8 and IE9. As mentioned in the introduction, this is a CSS-only based solution.
For the markup, I utilize the new HTML5 <figure> and <figcaption> elements, which are perfectly suited for this type of UI element:
<img height="215" width="215" src="660799.jpg" />
This is a sample caption that should not exceed the width of the image.
Pretty simple stuff – with the only real item of note being the
width attributes on the
<img> tag. These are required – and really – should be used regardless so that the browser can ‘smartly’ load the image with the proper dimensions.
Taking this markup and floating it to the left or right as you would normally do with an image, it’s easy to see the problem your going to run into. The caption text is going to keep flowing irregardless of the width of the image. To correct this, we simple do the following:
<figure> element to display as a table means that the content within will flow to the constraints (width) that is placed upon it. Remember back in the bad old days where you would often see a sidebar column sized at 1% so that it would only take up as much horizontal room as was required by the content within? This is the same sort of idea here.
The ‘table’ is being forced to a width of 87 pixels (a completely arbitrary number – I just happen to be a Penguins fan), but because the image inside of it has a width attribute set (in this case 215 pixels), it grows to accommodate the width of the content and as a result the caption ‘grows’ along with it.
A pretty nifty solution that works very well across all modern browsers I tested on – including IE8. Basically this will work on any browser that supports the
display: table CSS property.