DisgruntledGoat DisgruntledGoat - 6 months ago 16x
HTML Question

Limit text to the width of sibling image / auto width in CSS

I am essentially trying to create a version of the "figure" element (upcoming in HTML5), whereby I have an image with a short description below it.

However, I want to limit the width of this entire element to that of the image, so the text isn't wider than the image (wrapping to multiple lines if necessary).

Basic HTML:

<div class="figure">
<img src="..." alt="..." width="..." height="..." /><br />
A description for the image

I'm well-versed with CSS but I can't think of any pure CSS solution, without adding a
to the
to match the image width.

Update: After a bit of searching and thinking, the best method seems to be using an inline width on the div. I will keep the width attribute on the image, in case I wish the div to be a bit wider than the image (for example to accomodate a longer caption).

This approach also means I could have two images side-by-side with a caption below. If I have a set of images the same size, I can of course add an extra style to each

Thanks to everyone who answered!



div.figure img,
div.figure div.caption {
    width: 100%;
div.figure div {
    overflow: hidden;
    white-space: nowrap;

note: to enable wrapping just remove that last css line


<div class="figure" style="width:150px;">
    <img src="logo.png" alt="logo" />
    <div class="caption">A description for the image</div>

I've checked it in Chrome, Firefox and IE7 and it looks good in all three. I realise this has the width on the div and not the img, but at least you only need to set the width in one place. Short of using css-expressions (IE only) I can't see a way of setting the outer divs width to the width of the first child element.