Inline image and caption in article - conform caption's width to image's width

Posted by Micah on Stack Overflow See other posts from Stack Overflow or by Micah
Published on 2010-05-15T07:06:22Z Indexed on 2010/05/15 7:14 UTC
Read the original article Hit count: 444

Filed under:
|
|
|
|

Here's my code:

<div class="image">
<img src="image.jpg" alt="Image description" />
<p class="caption">This is the image caption</p>
</div>

Here's my CSS:

.image {
position: relative;
float: right;
margin: 8px 0 10px 10px;
}

.caption {
font-weight: bold;
color: #444666;
}

As is above, the caption will conform to the width of div.image. My problem is often the img varies in size, from 100px width to 250px width. I'd like to make the caption width conform to the corresponding width of the image, no matter the size.

While I'd love for this to be more semantic as well, I'm not sure how easy it would be to switch p.caption with img. Of course, I'd prefer that method but am taking this a step at a time.

Is there some jquery code that I can use to detect the width of the image and add that width as an inline style to the caption tag?

Is there a better way to do this? I'm open to suggestions.

© Stack Overflow or respective owner

Related posts about caption

Related posts about jQuery