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

帅比萌擦擦* 提交于 2019-12-11 03:27:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!