Set html figure-width to same as width of image it

2020-07-18 09:05发布

When having a image inside a figure-tag, the figure width is 100%. How do I make so that the the figure always will have the same width as the image? Here's my current code:

HTML:

<figure>
    <img src="http://www.google.com/images/srpr/logo3w.png" alt="" />
</figure>

CSS:

* {
    margin: 0;
    padding: 0;
}

figure {
    border: 1px solid red;
}

img {
    border: 1px solid blue;
    vertical-align: top;
}

标签: html css image
3条回答
何必那么认真
2楼-- · 2020-07-18 09:15

You could also do this with jquery, even though it's a bit of a hack:

var imgWidth = $("figure img").width();
     $("figure").width(imgWidth);

This is a fix if, for some reason, display: table isn't working for you in your css stack, or you need that element to be a different display type.

查看更多
唯我独甜
3楼-- · 2020-07-18 09:21

Event though you have not asked for any JS solution .here is my solution for your problem.

On image load change width and height of figure

Assuming figure is parent of img

   $(document).ready(function(){
         $("img").load(function(){

              $(this).parent().width( $(this).width());

           });   
    });
查看更多
啃猪蹄的小仙女
4楼-- · 2020-07-18 09:24

Add display:table to figure css like this

figure 
{
    display:table;
    border: 1px solid red;
}

JS Fiddle Demo

查看更多
登录 后发表回答