圖片維持等比例 (aspect ratio) 縮放

主要目的:讓圖片和裝圖片的容器在不同視窗寬度下,都能維持等比例縮放。

CSS 等比例縮放


1. With Img tag

<div class="parent">
  <div class="container">
    <img width="640" height="220" src="https://placehold.it/640x220">
  </div>
</div>
.parent {
  width: 100px;
}

.container {
  display: block;
  width: 100%;
  height: auto;
  position: relative;
  overflow: hidden;
  padding: 34.37% 0 0 0; /* 34.37% = 100 / (w / h) = 100 / (640 / 220) */
}

.container img {
  display: block;
  max-width: 100%;
  max-height: 100%;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

2. Img tag with ::before / ::after

<div class="parent">
  <img width="640" height="220" src="https://placehold.it/640x220">
</div>
.parent {
  position: relative;
  width: 100px;

  &::before {
    content: '';
    display: block;
    padding: 34.37% 0 0 0;
    overflow: hidden;
  }

  img {
    display: block;
    max-width: 100%;
    max-height: 100%;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
}

3. With css background-image

<div class="manage-section__img-wrapper">
   <div class="manage-section__hero-img"></div>
</div>
.manage-section__img-wrapper {
  display: block;
  position: relative;
  width: 100%;
  height: auto;
  padding-top: 52.63%; /* 1000 / 1900 * 100 = 52.6315% */
  overflow: hidden;
}

.manage-section__hero-img {
  display: block;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  max-width: 100%;
  max-height: 100%;
  background-image: url();
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50% 50%;
}

例如一張圖片寬度為 1900px、高度 1000px。

高度 / 寬度 * 100 = 原始寬高比

1000 / 1900 * 100 = 52.6315%

沒有寬度,沒有高度,純粹用 padding 撐起整個圖片。

以寬度為基準,隨著銀幕比例調整高度,代表比例為 52.63%。

  • Using padding-top to set the height from width.

  • Using position: absolute to put image in the padding space.

  • Using max-height and max-width to make sure the image will not over the parent element.

相關閱讀


CSS force image resize and keep aspect ratio - StackOverflow:上面的寫法是參考這篇

How TO - Aspect Ratio by W3Schools:有各個銀幕尺寸的比例

Aspect Ratio Boxes by Chris Coyier

Ratio Buddy:自動計算 padding-top 的小工具

1 Like

非常需要~
這樣省事多了~

不曉得 bootstrap 這個適不適用

使用的情境不太一樣 :expressionless:

當網頁有多個商品卡片時
我還希望圖片除了 width: 100% 等比例縮放外
即使商品圖每張 size 都不一樣 (有的胖、有的高)
裝圖片的容器都能固定尺寸顯示

1 Like