讓任意尺寸的圖片在固定寬高容器中完美置中,是前端高頻需求。本文對比四種主流方案:table-cell、Flexbox、Grid、absolute + transform,分析適用場景、瀏覽器支援度與優缺點,助你選擇最佳實作。
| 方案 | 核心 CSS | 支援度 | 優點 | 缺點 |
|---|---|---|---|---|
| table-cell | display:table-cell; vertical-align:middle; text-align:center |
IE8+ | 極簡、無額外標籤、舊專案相容佳 | 容器需固定高度;難以配合其他佈局 |
| Flexbox | display:flex; justify-content:center; align-items:center |
IE10+(部分前綴) | 語意清晰、支援換行、響應式友善 | IE10 需 -ms- 前綴 |
| Grid | display:grid; place-items:center |
現代瀏覽器(IE 不支援) | 最語意化、一行搞定、雙向對齊 | IE 完全不支援 |
| absolute + transform | position:relative 父 + position:absolute; top:50%; left:50%; transform:translate(-50%,-50%) 子 |
IE9+ | 不依賴容器高度、可脫離文檔流、動畫友善 | 需額外定位上下文、transform 可能模糊(舊瀏覽器) |
.container-tc {
width: 300px;
height: 300px;
border: 2px dashed #ccc;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.container-tc img {
max-width: 100%;
max-height: 100%;
vertical-align: middle; /* 修正 inline-block 基線問題 */
}
.container-flex {
width: 300px;
height: 300px;
border: 2px dashed #ccc;
display: flex;
justify-content: center; /* 水平置中 */
align-items: center; /* 垂直置中 */
}
.container-flex img {
max-width: 100%;
max-height: 100%;
object-fit: contain; /* 保持比例縮放 */
}
.container-grid {
width: 300px;
height: 300px;
border: 2px dashed #ccc;
display: grid;
place-items: center; /* 等同 align-items:center + justify-items:center */
}
.container-grid img {
max-width: 100%;
max-height: 100%;
}
.container-abs {
position: relative;
width: 300px;
height: 300px;
border: 2px dashed #ccc;
}
.container-abs img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
}
vertical-align: baseline,加 img { display: block; } 或 vertical-align: middle/top/bottom 即可。min-height。transform、filter、perspective 等屬性;或改用 Flex/Grid 避免 transform。