圖片高度未知、容器高度固定,需垂直居中顯示。現代 CSS 用 Flex/Grid 秒殺,但歷史專案需兼容 IE6/7,故保留經典方案供參考。
<div id="box">
<span><img src="demo.jpg" alt=""></span>
</div>
#box {
width: 500px;
height: 400px;
display: table; /* 關鍵:表格佈局 */
text-align: center; /* 水平置中 */
border: 1px solid #d3d3d3;
background: #fff;
}
#box span {
display: table-cell; /* 關鍵:表格單元格 */
vertical-align: middle; /* 垂直置中 */
}
#box img {
border: 1px solid #ccc;
max-width: 100%;
max-height: 100%;
}
/* === IE6/7 Hack === */
/* 條件註釋或 *html hack */
* html #box {
position: relative;
overflow: hidden;
}
* html #box span {
position: absolute;
left: 50%; top: 50%;
}
* html #box img {
position: relative;
left: -50%; top: -50%;
}
<div id="box">
<i></i><img src="logo.png" alt="">
</div>
#box {
width: 500px;
height: 400px;
display: table-cell; /* 容器變單元格 */
text-align: center;
vertical-align: middle; /* 垂直置中 */
border: 1px solid #d3d3d3;
background: #fff;
}
#box img {
border: 1px solid #ccc;
vertical-align: middle; /* 與輔助元素對齊 */
}
/* === IE6/7 專用 === */
* html #box i, *+html #box i {
display: inline-block;
height: 100%;
vertical-align: middle; /* 撐滿高度的幽靈元素 */
}
* html #box img, *+html #box img {
vertical-align: middle;
}
<div id="box">
<p><img src="demo.jpg" alt=""></p>
</div>
#box {
width: 500px;
height: 400px;
text-align: center;
border: 1px solid #d3d3d3;
background: #fff;
}
#box p {
width: 500px;
height: 400px;
line-height: 400px; /* 行高 = 容器高 */
margin: 0;
}
/* 標準瀏覽器:偽元素撐開 */
#box p::before {
content: ".";
margin-left: -5px;
font-size: 10px;
visibility: hidden;
display: inline-block;
vertical-align: middle;
height: 100%;
}
#box p img {
vertical-align: middle;
border: 1px solid #ccc;
/* IE6/7 Expression 動態計算 margin-top */
*margin-top: expression((400 - this.height) / 2);
}
.modern-img-center {
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 400px;
border: 1px solid #d3d3d3;
}
.modern-img-center img {
max-width: 100%;
max-height: 100%;
/* 或 object-fit: contain; width: 100%; height: 100%; */
}
/* Grid 方案 */
.grid-img-center {
display: grid;
place-items: center;
width: 500px;
height: 400px;
}
| 方案 | 原理 | 現代瀏覽器 | IE6/7 | 代碼複雜度 | 推薦指數 |
|---|---|---|---|---|---|
| Table/Table-cell | 表格單元格 vertical-align | ✅ 完美 | ⚠️ 需 Hack | 中 | ⭐⭐⭐ (兼容舊項目) |
| Inline-block 幽靈元素 | 滿高 inline-block 對齊 | ✅ 完美 | ✅ 原生支援 | 低 | ⭐⭐⭐⭐ (IE 兼容最佳) |
| 偽元素 + line-height | 行高撐開 + 偽元素對齊 | ✅ 完美 | ⚠️ 需 Expression | 中 | ⭐⭐ (Expression 有效能風險) |
| Flex/Grid | 現代佈局模組 | ✅ 完美 | ❌ 不支援 | 極低 | ⭐⭐⭐⭐⭐ (新專案首選) |
expression 在 IE 中會頻繁重算,影響效能,慎用於大量圖片max-width: 100%; max-height: 100% 防止撐破容器<i> 可換為 <span> 或任意內聯元素,語義化建議用 <span class="valign-fix">