views:

82

answers:

1

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.

A: 

You can do something like this:

$(window).load(function() {
  $(".image p.caption").each(function() {
    $(this).width($(this).siblings("img").width()).prependTo($(this).parent());
  });
});

This also does the moving of <p> before the <img> which you asked for.

For testing, you can see a working demo here.

Nick Craver
Oh wow, awesome! That's amazing and worked exactly as you said. Thank you!Could you provide this code without it making the paragraph and image switching places? I can actually manually do this in the code itself, but the reason I haven't is because of positioning. Because the caption paragraphs vary in length, I can't make them clear the images since they are assigned position:absolute in the CSS.
Micah
@Micah - Just lop off the `.prependTo($(this).parent())` on the end so it's just `$(this).width($(this).siblings("img").width());` :)
Nick Craver
Thanks so much, Nick!
Micah
@Micah - Welcome :)
Nick Craver