圖片為置換元素,預設 vertical-align: baseline 導致底部留白;高寬未知時傳統 vertical-align: middle 需配合行內區塊或表格單元格。
.container {
display: table-cell;
width: 200px;
height: 200px;
vertical-align: middle;
text-align: center;
border: 1px solid #eee;
}
.container img {
vertical-align: middle;
max-width: 100%;
max-height: 100%;
}
/* IE6/7 Hack */
* html .container { display: block; font-size: 175px; font-family: Arial; }
*+html .container { display: block; font-size: 175px; font-family: Arial; }
.container {
display: flex;
justify-content: center; /* 水平置中 */
align-items: center; /* 垂直置中 */
width: 200px;
height: 200px;
border: 1px solid #eee;
}
.container img {
max-width: 100%;
max-height: 100%;
}
.container {
display: grid;
place-items: center; /* 等同 justify-items + align-items */
width: 200px;
height: 200px;
border: 1px solid #eee;
}
.container img {
max-width: 100%;
max-height: 100%;
}
.container {
position: relative;
/* 容器可無固定高度 */
}
.container img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
}
.container::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.container img {
display: inline-block;
vertical-align: middle;
max-width: 100%;
max-height: 100%;
}
| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 現代專案、IE10+ | Flexbox / Grid | 語意清晰、功能強大、易維護 |
| 需支援 IE8/9 | Table-Cell | 相容性最好、無 Hack |
| 容器高度不固定 | Absolute + Transform | 不依賴容器高度 |
| 不想改變容器 display | 幽靈元素 | 最小侵入性 |
max-width: 100%; max-height: 100% 防止圖片撐破容器aspect-ratiovertical-align: middle 基線是 小寫 x 高度一半,非絕對中心,大圖差異明顯