萬盛學電腦網

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

CSS 限制圖片最大寬度並保持比例自適應

核心 CSS(現代標準)

img {
  max-width: 100%;   /* 不超過容器寬度 */
  height: auto;      /* 關鍵:保持原始長寬比 */
}

適用於所有置換元素(img, video, canvas, svg, object...)。

指定最大像素尺寸(如縮圖 800px)

.limit-800 { max-width: 800px; height: auto; }

WordPress 主題實戰範例

.entry-content img {
  max-width: 550px;                 /* 文章區最大寬度 */
  width: expression(this.width > 550 ? '550px' : 'auto'); /* IE6/7 Hack */
  height: auto;
}

注意:Expression 為 IE 專屬、效能差、安全風險,**新專案請勿使用**。

JavaScript 兜底方案(通用、可控)

function autoFitImage(img, maxW, maxH) {
  const image = new Image();
  image.onload = () => {
    let { width, height } = image;
    if (width > maxW || height > maxH) {
      const ratio = Math.min(maxW / width, maxH / height);
      img.width = width * ratio;
      img.height = height * ratio;
    }
  };
  image.src = img.src;
  img.style.cursor = 'zoom-in';
  img.onclick = () => window.open(img.src, '_blank', 'width=800,height=600');
}

// 使用:

現代最佳實踐:響應式圖片

<picture>
  <source media="(max-width: 480px)" srcset="img-480w.jpg">
  <source media="(max-width: 800px)" srcset="img-800w.jpg">
  <img src="img-1200w.jpg" alt="..." loading="lazy">
</picture>
  • 瀏覽器自動選擇最適合尺寸的圖片來源。
  • loading="lazy" 原生延遲載入,提升首屏速度。
  • 配合 CDN 即時裁切(如 Cloudinary、Imgix)更靈活。
copyright © 萬盛學電腦網 all rights reserved