圖片為替換元素,預設 inline 行為但有固有尺寸。垂直置中需解決:容器高度已知/未知、圖片尺寸已知/未知、多行文字混排、響應式適配。
| 方案 | 容器高度 | 圖片尺寸 | 瀏覽器支援 | 複雜度 | 推薦指數 |
|---|---|---|---|---|---|
| Flexbox | 任意 | 任意 | IE10+ | 極低 | ⭐⭐⭐⭐⭐ |
| Grid | 任意 | 任意 | 現代瀏覽器 | 極低 | ⭐⭐⭐⭐⭐ |
| Table-Cell | 任意 | 任意 | IE8+ | 低 | ⭐⭐⭐⭐ |
| 偽元素輔助 | 已知 | 任意 | IE8+ | 中 | ⭐⭐⭐ |
| Absolute + Transform | 已知 | 任意 | IE9+ | 中 | ⭐⭐⭐ |
| Absolute + 負 Margin | 已知 | 已知 | 全瀏覽器 | 低 | ⭐⭐ |
.img-center-flex {
display: flex;
align-items: center; /* 垂直置中 */
justify-content: center; /* 水平置中 */
min-height: 300px; /* 容器需有高度 */
}
.img-center-flex img {
max-width: 100%;
max-height: 100%;
object-fit: contain; /* 保持比例縮放 */
}
.img-center-grid {
display: grid;
place-items: center; /* 同時水平垂直置中 */
min-height: 300px;
}
.img-center-grid img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
.img-center-table {
display: table-cell;
vertical-align: middle;
text-align: center;
height: 300px; /* 必須固定高度 */
width: 400px; /* 可選 */
}
.img-center-table img {
vertical-align: middle;
max-width: 100%;
max-height: 100%;
}
.img-center-ghost {
text-align: center;
height: 300px; /* 容器固定高度 */
}
.img-center-ghost::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.img-center-ghost img {
display: inline-block;
vertical-align: middle;
max-width: 100%;
max-height: 100%;
}
.img-center-absolute {
position: relative;
height: 300px;
}
.img-center-absolute img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
}
.responsive-img-container {
position: relative;
width: 100%;
padding-top: 75%; /* 4:3 比例容器 */
overflow: hidden;
}
.responsive-img-container img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
| 值 | 行為 | 適用場景 |
|---|---|---|
contain | 完整顯示、保持比例、可能留白 | 圖片展示、Logo、頭像 |
cover | 填滿容器、保持比例、裁切溢出 | 背景圖、Banner、卡片封面 |
fill | 拉伸填滿、不保持比例 | 極少用 |
none | 原始尺寸、不縮放 | 精確像素控制 |
scale-down | 取 none 或 contain 较小者 | 防止放大失真 |
alt 屬性描述圖片內容。alt="" 或 CSS 背景圖。object-fit 不影響 SEO,圖片仍被索引。任意尺寸圖片垂直置中,**現代首選 Flex/Grid**,**舊環境用 Table-Cell/偽元素**,**特殊定位需求用 Absolute+Transform**。關鍵在於容器是否有高度、是否需響應式、瀏覽器支援基線。善用 object-fit 控制縮放行為,配合 max-width/height: 100% 防止溢出,建立專案通用 .img-center、.img-cover 工具類。