max-widthFirefox、Chrome、Safari、Edge、IE7+ 皆支援 max-width,可限制圖片最大顯示寬度,超過則等比縮小,未超過則保持原尺寸:
.fit-image {
border: 0;
max-width: 500px; /* 最大顯示寬度 500px */
height: auto; /* 保持比例 */
}
IE6 不支援 max-width,可利用 IE 專有 expression 動態計算寬度:
.fit-image {
border: 0;
max-width: 500px; /* 現代瀏覽器生效 */
width: expression(
(function(img) {
img.onload = function() {
this.style.width = ''; // 重置
this.style.width = (this.width > 500) ? '500px' : this.width + 'px';
};
return '120px'; // 載入前暫時寬度
})(this)
);
}
onload。this.width 是否大於 500px。'120px' 避免載入瞬間版面跳動。/* 全域重置 */
img {
max-width: 100%;
height: auto;
vertical-align: middle; /* 消除底部間隙 */
display: block; /* 避免行內基線間隙 */
}
/* 特定容器限制 */
.container { max-width: 800px; margin: 0 auto; }
.container img { max-width: 100%; }
srcset + sizes + <picture>針對不同裝置提供不同解析度圖片,配合 CSS 斷點,實現真正的響應式圖片:
<picture>
<source media="(max-width: 480px)" srcset="img-small.jpg">
<source media="(max-width: 1024px)" srcset="img-medium.jpg">
<img src="img-large.jpg" alt="響應式圖片">
</picture>
現代專案僅需 max-width: 100%; height: auto; 即可解決 99% 場景。IE6 相容請評估成本效益,建議優雅降級(顯示原圖或略過縮放)而非使用 Expression。