如何使图像标题宽度与图像宽度匹配?

时间:2015-06-06 18:24:33

标签: html css css3

我试图设计这个:

<div class="figure">
  <img src="/some/image.jpg">
  <p class="caption">
    <span class="caption-text">Some caption of any length</span>
   </p>
</div>

因此标题位于阴影框中,与图像的宽度相同。请注意,.figure有时可以位于表格中的<td>内,以防万一。它也不应超过父元素的宽度(在必要时缩小图像)。

这是我到目前为止所拥有的:

.caption-text {
  font-size: 14px;
  font-family: Lato, proxima-nova, 'Helvetica Neue', Arial, sans-serif;
  font-weight: normal;
  line-height: 0px;
}

.figure {
  max-width: 100%;
  display: inline-block;
  position: relative;
}

.figure img {
  vertical-align: top;
  margin-bottom: 3px;
}

.caption {
  display: block;
  width: 100%;
  position: absolute;
  padding: 10px;
  background-color: #e3e3e3;
  box-sizing: border-box;
  margin: 0;
}
<div style="width:500px">
  <h1>Some Title</h1>

  <!--part I want to style-->
  <div class="figure">
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150">
    <p class="caption">
      <span class="caption-text">Some caption of any length. Should wrap and push content down when longer than the image.</span>
    </p>
  </div>
  
  <p>Some text which should always go below the caption. When positioned absolutly the caption overlays this text, instead of pushing it down below.</p>

</div>

问题在于,将.caption设为position:absolute;会使其不再影响其他元素的流量,因此它会覆盖其下方的内容而不是将其推下来。

html标记是自动生成的,我无法编辑其中任何一个,所以我想知道这是否可能纯css

2 个答案:

答案 0 :(得分:18)

您可以使用CSS display:table + table-caption解决方案。

&#13;
&#13;
.figure {
  display: table;
  margin: 0;
}

.figure img {
  max-width: 100%;
}

.figcaption {
  display: table-caption;
  caption-side: bottom;
  background: pink;
  padding: 10px;
}
&#13;
<h3>Example of small image</h3>
<figure class="figure">
  <img src="//dummyimage.com/300x100" alt="">
  <figcaption class="figcaption">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</figcaption>
</figure>

<h3>Example of large image</h3>
<figure class="figure">
  <img src="//dummyimage.com/900x100" alt="">
  <figcaption class="figcaption">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</figcaption>
</figure>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

我包含了一个更通用的选项,不需要表格布局。这意味着您可以添加更多的孩子,而不必担心表格布局将如何影响他们。您还可以选择哪些子级将“扩展”容器,而哪些则不会。

它所需要的只是外部元素是display: inline-block;position: absolute;或任何其他“缩小以适合”类型的节点。

.container {
  display: inline-block;
}

.no-expand {
  box-sizing: border-box;
  width: 0px;
  min-width: 100%;
  
  background: pink;
  padding: 10px;
}
<h3>Example of small image</h3>
<div class="container">
  <img src="//dummyimage.com/300x100" alt="">
  <div class="no-expand">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
</div>

<h3>Example of large image</h3>
<div class="container">
  <img src="//dummyimage.com/900x100" alt="">
  <div class="no-expand">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
</div>