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

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


回首忆惘然
浏览 104回答 2
2回答

DIEA

更新您的代码,如下所示:.container {&nbsp; width: 80%;&nbsp; height: 48vw;&nbsp; /* 4:3 */&nbsp; margin: 5px auto;&nbsp; text-align: center;}.img-wrap {&nbsp; background-color: #efe;&nbsp; height: 100%;&nbsp; display: inline-block;&nbsp; position: relative;}img {&nbsp; max-width: 100%;&nbsp; height: 100%;&nbsp; display: block;&nbsp; object-fit: contain; /*or cover if you want to cover all the area*/&nbsp; object-position: bottom;}.caption {&nbsp; position: absolute;&nbsp; left: 0;&nbsp; right: 0;&nbsp; bottom: 0;&nbsp; color: #fff;&nbsp; background-color: rgba(153, 153, 153, 0.541)}<div class="container">&nbsp; <div class="img-wrap">&nbsp; &nbsp; <img src="https://i.picsum.photos/id/10/400/600.jpg">&nbsp; &nbsp; <div class="caption">Caption Content</div>&nbsp; </div></div><div class="container">&nbsp; <div class="img-wrap">&nbsp; &nbsp; <img src="https://i.picsum.photos/id/10/600/300.jpg">&nbsp; &nbsp; <div class="caption">Caption Content</div>&nbsp; </div></div>

宝慕林4294392

不要position absolute图像,另外,如果标题是图像的同级,设置父级的大小,如果父级的宽度和高度将图像设置为 100%然后你可以简单地使用text-align: center标题上的 将其居中。编辑 :保留现有的标题样式以进行定位小提琴: https:&nbsp;//jsfiddle.net/hellooutlook/6ep4Lofz/4/
打开App,查看更多内容
随时随地看视频慕课网APP