如何使<figcaption>的宽度与<figure>标签内的<img>的宽度相匹配?

rkh*_*hff 46 css html5

说,我得到了这个代码:

<figure>
 <img src="bunnyrabbit.jpg" width="200" height="150" alt="An image of a bunny rabbit." />
 <figcaption>Bunny rabits are cuddly and fluffy creatures with big ears. They eat carrots.</figcaption>
</figure>
Run Code Online (Sandbox Code Playgroud)

如果我不使用任何CSS,figcaption将扩展图元素的宽度超过200px.我怎么能阻止这个?

我知道我可以通过指定图元素(<figure style="width:200px;">)的宽度来强制figcaption中的文本换行,但我真的不想对每个图像使用它.

Mar*_*ner 45

将此代码添加到<figure><figcaption>CSS-属性帮我同样的问题.此外,它还保留了图像和字幕的响应.

figure { display: table; }


figcaption { display: table-caption; caption-side: bottom ; }
Run Code Online (Sandbox Code Playgroud)
  1. 添加display: table;设置阶段.

  2. display: table-caption;单独添加将标题放在图像顶部,该caption-side属性指定表标题的位置bottom,top默认为.


rob*_*rtc 28

这将figcaption并排放置img:

figure {
    display: table;
}
img, figcaption {
    display: table-cell;
    vertical-align: bottom;
}
figcaption {
    padding-left: 4px;
}
Run Code Online (Sandbox Code Playgroud)

这是一个例子.然而,我并不完全清楚你想要实现的目标 - 你在问题中说你希望figure保持200px的宽度,但是你评论你希望它figcaption出现在右边,这会使得figure更宽.如果你想要的只是figcaption限制图像的宽度,这应该工作:

figure {
    display: table;
    width: 1px; /* This can be any width, so long as it's narrower than any image */
}
img, figcaption {
    display: table-row;
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*eld 18

另一种解决方案:使用内在宽度

刚刚成立width: min-content;的上figure元素

演示(IE除外)

figure {
  width: -webkit-min-content;
  width: -moz-min-content;
  width: min-content;
}
Run Code Online (Sandbox Code Playgroud)
<figure>
  <img src=" http://placehold.it/200x150" width="200" height="150" alt="An image of a bunny rabbit." />
  <figcaption>Bunny rabits are cuddly and fluffy creatures with big ears. They eat carrots.</figcaption>
</figure>
Run Code Online (Sandbox Code Playgroud)

注意: 浏览器支持是正常的,除了IE,但他们正在考虑实现这一点

  • 这几乎是一个完美的解决方案,只是它根本不适用于响应式图像。要看到此中断,您所需要做的就是 add`img { max-width: 100%; 高度:自动!重要;}` 到演示小提琴,如下所示:http://jsfiddle.net/jwilson3/ta17f9Lh/ (2认同)
  • @Archagon 不知道这有什么帮助。它会导致图像停止响应... http://jsfiddle.net/jwilson3/Lhrjew6v/ 希望有一个有效的示例。 (2认同)
  • 但如果标题变窄,图像也会缩小吗? (2认同)