固定寬高容器(如 300x300px)內放置尺寸未知的圖片,需求:
<img src="img.png" onload="resize(this, 100, 100)">
function resize(el, maxW, maxH) {
if (el.width > maxW || el.height > maxH) {
if (el.width / el.height > maxW / maxH) el.width = maxW;
else el.height = maxH;
}
}
缺點:需等圖片載入、JS 執行延遲、維護成本高。
.box {
width: 300px;
height: 300px;
text-align: center; /* 行內/行內區塊水平置中 */
border: 1px solid #ccc;
}
.box img {
max-width: 100%; /* 不超出容器寬 */
max-height: 100%; /* 不超出容器高 */
width: auto; /* 覆寫 HTML width 屬性 */
height: auto; /* 覆寫 HTML height 屬性 */
vertical-align: middle; /* 垂直置中 (配合 line-height 或偽元素) */
}
/* IE7 垂直置中補丁:容器加 line-height = height,或使用偽元素 */
.box::before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
<div class="box"><img src="image-url.png" alt=""></div>
max-width:100%; max-height:100% 限制上限,配合 width:auto; height:auto 保持原始比例縮放。text-align:center 處理水平置中。display:flex; align-items:center; justify-content:center;;IE7 需 line-height 或偽元素 inline-block hack。