Limit text to the width of sibling image / auto width in CSS

后端 未结 5 799
不知归路
不知归路 2020-12-03 01:28

I am essentially trying to create a version of the \"figure\" element (upcoming in HTML5), whereby I have an image with a short description below it.

However, I want

相关标签:
5条回答
  • 2020-12-03 01:48

    This could also be accomplished using 'display: table-caption' for the caption, as follows:

    HTML

    <div class="wrapper">
      <img src="image.jpg" />
      <div class="caption">My caption...</div>
    </div>
    

    Stylesheet

    .wrapper {
      display: table;
    }
    
    .caption {
      display: table-caption;
      caption-side: bottom;
    }
    

    This block can also be floated left of right of other text. I've tested this in IE8+. Here's a JSBin example: http://jsbin.com/xiyevovelixu/1

    0 讨论(0)
  • 2020-12-03 01:54

    I had the same problem and after reading this decided to use an inline-style on the surrounding element. Seems the better solution over using a table to me.

    0 讨论(0)
  • 2020-12-03 01:58

    You could use the display:table solution for all other browsers, and a CSS Behaviour for Internet Explorer.

    0 讨论(0)
  • 2020-12-03 02:04

    Stylesheet

    div.figure img,
    div.figure div.caption {
        width: 100%;
    }
    div.figure div {
        overflow: hidden;
        white-space: nowrap;
    }
    

    note: to enable wrapping just remove that last css line

    HTML

    <div class="figure" style="width:150px;">
        <img src="logo.png" alt="logo" />
        <div class="caption">A description for the image</div>
    </div>
    

    I've checked it in Chrome, Firefox and IE7 and it looks good in all three. I realise this has the width on the div and not the img, but at least you only need to set the width in one place. Short of using css-expressions (IE only) I can't see a way of setting the outer divs width to the width of the first child element.

    0 讨论(0)
  • 2020-12-03 02:05

    For setting the width to match the image automatically you could use

    .figure {
      display: table;
      width: 1px;
    }
    

    This makes the div behave like a table (not supported in Internet Explorer). Or you could use a table instead of the div. I don't think there is another way of setting the width automatically.

    Edit: The simplest way is to forget about the auto width and set it by hand. If it is really needed you can use JavaScript or a table. In this case the use of a table is not so ugly because you are addressing a limitation of the HTML version. In the case of server-side scripting you could also set the width when generating the page.

    0 讨论(0)
提交回复
热议问题