早期響應式佈局中,常需容器隨寬度變化保持固定比例(如 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:9 | 56.25% | 視頻播放器、YouTube 嵌入 |
| 4:3 | 75% | 傳統投影、iPad 螢幕截圖 |
| 3:2 | 66.66% | 35mm 相片、部分相機預覽 |
| 1:1 | 100% | 頭像、商品圖、Instagram 風格 |
| 21:9 | 42.85% | 超寬電影、時間軸橫幅 |
.ratio-box img {
width: 100%;
height: 100%;
object-fit: cover; /* 裁切填充 */
object-position: center; /* 聚焦點 */
}
.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;
}
.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%;
}
}
aspect-ratio 配合 min-height 更可控。aspect-ratio 即可,無需包裹層。background-size: cover + aspect-ratio 替代舊 hack。「理解padding-bottom%基於寬度計算的機制,是理解 CSS 盒模型佈局邏輯的關鍵一課;但新項目請直接用aspect-ratio。」