最适合带有标题的 img 到元素中

best fit img with caption into element

构建图像幻灯片,我有一个任意大小和宽高比的容器 div,我必须将图像最佳地放入其中,居中,在图像底部覆盖标题并适合其宽度。迄今为止我最好的解决方案是将图像和标题包含在容器的 child 元素中,但我无法将其居中。这应该是一件如此简单的事情,我简直不敢相信它不是在盯着我看,而是我看不见。下面的代码使用纵向格式图像,但我也需要它来处理横向。我正在使用 React,所以 jQuery 不可用。

.container {
  position: relative;
  width: 80%;
  height: 48vw;
  /* 4:3 */
  margin: 0 auto;
  display: flex;
  justify-content: center;
}

.img-wrap {
  background-color: #efe;
}

img {
  position: absolute;
  max-width: 100%;
  max-height: 100%;
}

.caption {
  position: absolute;
  bottom: 0;
  color: #fff;
  background-color: rgba(153, 153, 153, 0.541)
}
<div class="container">
  <div class="img-wrap">
    <img src="https://png.pngtree.com/thumb_back/fw800/background/20190223/ourmid/pngtree-full-aesthetic-aurora-night-sky-background-skystarry-skystarnight-viewbackgroundstar-image_87582.jpg" height="1600px">
    <div class="caption">Caption Content</div>
  </div>
</div>

不要position absolute图片,

如果标题是图像的同级图像,

设置 parent 的大小,如果 parent 的宽度和高度

,则将图像设置为 100%

然后您可以简单地使用标题上的 text-align: center 将其居中。

编辑:

  • 保留标题的现有样式以进行定位

fiddle : https://jsfiddle.net/hellooutlook/6ep4Lofz/4/

像下面这样更新您的代码:

.container {
  width: 80%;
  height: 48vw;
  /* 4:3 */
  margin: 5px auto;
  text-align: center;
}

.img-wrap {
  background-color: #efe;
  height: 100%;
  display: inline-block;
  position: relative;
}

img {
  max-width: 100%;
  height: 100%;
  display: block;
  object-fit: contain; /*or cover if you want to cover all the area*/
  object-position: bottom;
}

.caption {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  color: #fff;
  background-color: rgba(153, 153, 153, 0.541)
}
<div class="container">
  <div class="img-wrap">
    <img src="https://i.picsum.photos/id/10/400/600.jpg">
    <div class="caption">Caption Content</div>
  </div>
</div>

<div class="container">
  <div class="img-wrap">
    <img src="https://i.picsum.photos/id/10/600/300.jpg">
    <div class="caption">Caption Content</div>
  </div>
</div>