为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
回首忆惘然 2023-08-21 16:08:49
构建图像幻灯片时,我有一个任意大小和纵横比的容器 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>
查看完整描述

2 回答

?
DIEA

TA贡献1820条经验 获得超2个赞

更新您的代码,如下所示:


.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>


查看完整回答
反对 回复 2023-08-21
?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

不要position absolute图像,

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

设置父级的大小,如果父级的宽度和高度将图像设置为 100%

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

编辑 :

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

小提琴: https: //jsfiddle.net/hellooutlook/6ep4Lofz/4/


查看完整回答
反对 回复 2023-08-21
  • 2 回答
  • 0 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信