iT邦幫忙

0

讓各種不同size比例的圖片自適應填入div內的方法?

請問各位大大

圖片顯示根據圖片父元素的div比例和圖原始比例
自動resize填滿div高度或是寬度然後不能變形 + 水平垂直置中

有辦法純粹只靠css控制嗎?有比較general的方法嗎?

實際結構

    <style>
  #imageContainer {
    width: 100vw;
    height: 100vh;
  }

  #imageDiv {
    aspect-ratio: 4/3;
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    background-color: beige;
    margin: auto;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    overflow: hidden;
    display: flex;
    align-items: center;
  }

  #imageDiv img {
    max-height: 100%;  
    max-width: 100%; 
    margin: auto;
  }
    </style>
    <body style="margin: 0;">

      <div id="imageContainer">
        <div id="imageDiv">
          <img src="image1.jpg" alt="">

        </div>
      </div>

    </body>

有兩種不同的圖
第一張圖寬比高大(1170x780)
第二張圖高比寬大(687x1030)

第一張的狀況,左右並沒有填滿
https://ithelp.ithome.com.tw/upload/images/20211118/20126597pSRoVRP3pf.png

我如果加上

width: 100%;
height: auto;

就能把左右填滿

但是當我換成另一種比例的圖,第二張的狀況
https://ithelp.ithome.com.tw/upload/images/20211118/20126597pxtgm9a8lz.png

就會變形因為寬高比不一樣

必須反過來變成

width: auto;
height: 100%;

但第一張的狀況又無法適用會變形

看更多先前的討論...收起先前的討論...
用 background
不能用background-image....,一定要用img element...
Mao iT邦新手 1 級 ‧ 2021-11-18 16:31:01 檢舉
看你沒有按最佳解答的習慣,這裡我就只給你提示查詢方向就不 Demo 了~可以參考 Bootstrap 的 Ratio,就可以實現 CSS 等比例自動填滿父容器的大小,還可以依照你想要的寬高比調整。
用 ratio 應該會變形哦
依照你的需求,這應該是你要的
https://codepen.io/gitoxxvn/pen/PoKVpWX
那張左右沒有填滿的圖,當我把視窗縮小,效果就正常了
不知道是不是因為我的div(放圖片的)上還有一層div造成的?因為我需要在中間固定一個4:3大小的div(放圖片的)
greenriver iT邦研究生 5 級 ‧ 2021-11-18 16:54:07 檢舉
不管怎樣都是會變形,
唯一解,只有請設計師提供相同寬高的圖片
試試看 object-fit: cover; 吧
還是用js控制好了....
Mao iT邦新手 1 級 ‧ 2021-11-18 17:10:34 檢舉
我用 Bootstrap 的 Ratio 是利用 after 偽元素來遮蔽多餘的部分,形成設定的比例,再來就是 width: 100%; object-fit: cover; 讓圖片自己適應寬度,object-position: center; 調整圖片置中,[範例,最近的作品,裡面的圖片都是使用 Ratio 來達到自己適應相框,並置中](https://johnsonmao.github.io/taiwan_tourguide/#/home)
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答