萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 等比縮放容器:用 padding-bottom 實現響應式固定寬高比

核心痛點:CSS 無原生「寬高比」屬性(直到 aspect-ratio 出現前)

早期響應式佈局中,常需容器隨寬度變化保持固定比例(如 16:9 視頻、4:3 圖片、1:1 卡片)。width 可設百分比,但 height 無法直接跟隨。經典 Hack:利用 padding-bottom 百分比基於父元素 寬度 計算的特性。

經典代碼模式

.ratio-box {
  width: 100%;           /* 或任意百分比/固定寬度 */
  height: 0;             /* 高度歸零 */
  padding-bottom: 56.25%; /* 16:9 = 9/16 = 56.25% */
  position: relative;    /* 為絕對定位內容建立定位上下文 */
  background-color: #f00; /* 視覺化調試 */
}

.ratio-box > .content {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  /* 內容區填滿容器 */
}

常見比例對照表

比例padding-bottom典型場景
16:956.25%視頻播放器、YouTube 嵌入
4:375%傳統投影、iPad 螢幕截圖
3:266.66%35mm 相片、部分相機預覽
1:1100%頭像、商品圖、Instagram 風格
21:942.85%超寬電影、時間軸橫幅

進階應用場景

1. 圖片自適應填充(配合 object-fit)

.ratio-box img {
  width: 100%;
  height: 100%;
  object-fit: cover;      /* 裁切填充 */
  object-position: center; /* 聚焦點 */
}

2. 響應式 iframe 嵌入(地圖、視頻、第三方組件)

.embed-responsive {
  position: relative;
  padding-bottom: 56.25%;
  height: 0;
  overflow: hidden;
}
.embed-responsive iframe {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
  border: 0;
}

3. 多列等高卡片網格

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}
.card {
  display: flex;
  flex-direction: column;
}
.card-media {
  width: 100%;
  padding-bottom: 75%; /* 4:3 */
  position: relative;
}
.card-media img { /* 同 object-fit 寫法 */ }
.card-body { flex: 1; display: flex; flex-direction: column; }

現代最佳實踐:aspect-ratio(CSS 2021,主流瀏覽器已全支持)

.modern-ratio {
  width: 100%;
  aspect-ratio: 16 / 9; /* 或 1 / 1, 4 / 3 */
  /* 無需 height:0 + padding-bottom hack */
}

優雅降級策略:

.ratio-box {
  width: 100%;
  aspect-ratio: 16 / 9;
  /* 給不支持的舊瀏覽器 */
  @supports not (aspect-ratio: 1) {
    height: 0;
    padding-bottom: 56.25%;
  }
}

避坑指南

  • 內容撐開:若內容高度超過比例高度,舊版 hack 會溢出。現代 aspect-ratio 配合 min-height 更可控。
  • Flex/Grid 子元素:直接在子元素設 aspect-ratio 即可,無需包裹層。
  • 背景圖片:background-size: cover + aspect-ratio 替代舊 hack。
「理解 padding-bottom% 基於寬度計算的機制,是理解 CSS 盒模型佈局邏輯的關鍵一課;但新項目請直接用 aspect-ratio。」
copyright © 萬盛學電腦網 all rights reserved