亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

最適合帶有標題的 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 關注
  • 201 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號