Inline image and caption in article - header width compatibility with image width

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 stated above, the title will fit the width of the div.image. My problem is often img changes in size, from 100px width to 250px wide. I would like the label width to match the corresponding image width, regardless of size.

While I would have liked it to be more semantic, I'm not sure how easy it would be to switch p.caption to img . Of course, I would prefer this method, but I am doing it one step at a time.

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

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

+2


a source to share


1 answer


You can do something like this:

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

      



This is also the move <p>

to <img>

that you requested.

For testing, you can see a working demo here .

0


a source







All Articles