仅使用 css 自动调整图像下方的文本

Autofit text under image with only css

我正在尝试在图像下布置一些文本,使图像决定容器的宽度,文本换行成几行以适应宽度。

我当前的代码如下所示:

.image-container {
 display: inline-block;
 text-align: center;
    padding: 6px;
 background-color: red; /* To highlight container size */
}

.image {
 height: 120px;
}

.text-wrapper {
 position:relative;
 width: 100%;
}

.text {
 position:absolute;
 left:0px;
 top:100%;
 right:0px;
}
<div class='image-container'>
 <img src='http://i.imgur.com/nV2qBpe.jpg' class="image">
 <div class='text-wrapper'>
  <p class='text'>Some text that may need to wrap into multiple lines</p>
 </div>
</div>

但是如您所见,由于文本是绝对定位的,它不是容器高度的一部分,因此无法在我页面的其余部分正确布局。

如何正确解决这个问题?顺便说一句,我宁愿失去一些浏览器兼容性也不愿使用 js。

试试这个

.image-container {
  display: table;
  width: 1%;
}

img {
  height: 120px;
}

.text {
  overflow: hidden;
}
<div class='image-container'>
 <img src='http://i.imgur.com/nV2qBpe.jpg' class="image">
 <div class='text-wrapper'>
  <p class='text'>Some text that may need to wrap into multiple lines</p>
 </div>
</div>

这是您可以尝试的另一种解决方案

.image-container {
  display: table;
}

img {
  height: 120px;
}

.text-wrapper {
  display: table-caption;
  caption-side: bottom;
}
<div class='image-container'>
 <img src='http://i.imgur.com/nV2qBpe.jpg' class="image">
 <div class='text-wrapper'>
  <p class='text'>Some text that may need to wrap into multiple lines</p>
 </div>
</div>