问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/2839248/inline-image-and-caption-in-article-conform-captions-width-to-images-width