萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 等比例縮放圖片:max-width/height 與 IE 兼容方案

現代標準寫法(全瀏覽器)

.responsive-img {
  max-width: 100%;
  height: auto; /* 保持比例 */
}

適用於 <img>、<video>、<canvas> 等置換元素。

固定最大尺寸(如縮圖 50×50)

.thumb {
  max-width: 50px;
  max-height: 50px;
  width: auto; height: auto;
}

IE6/7 兼容:CSS Expression(不推薦新專案)

* html .thumb { /* IE6-7 only */
  width: expression(this.width > 50 && this.width > this.height ? '50px' : 'auto');
  height: expression(this.height > 50 ? '50px' : 'auto');
}

缺點:Expression 會頻繁重算、阻塞渲染、安全風險,微軟已棄用。

現代最佳實踐

  1. 伺服器端生成多種尺寸圖片(srcset/picture)。
  2. 前端僅需 img { max-width: 100%; height: auto; }。
  3. 若必須前端裁切,使用 object-fit: cover + 固定容器尺寸。
copyright © 萬盛學電腦網 all rights reserved