Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Thu nhỏ ảnh responsive với CSS (max-width: 100%)

Responsive Image: max-width: 100%

Để ảnh **tự động thu nhỏ** vừa container trên mobile/tablet nhưng **không phóng to** vượt kích thước gốc, dùng `max-width: 100%` + `height: auto`.

Ví dụ cơ bản

<!DOCTYPE html>
<html>
<head>
  <style>
    img {
      max-width: 100%;   /* Không bao giờ rộng hơn container */
      height: auto;      /* Giữ tỷ lệ khung hình */
    }
  </style>
</head>
<body>
  <img src="coding_ground_home.jpg" alt="Online Compiler" width="300" height="300">
</body>
</html>

Tại sao không dùng width: 100%?

Thuộc tínhHành viVấn đề
width: 100%Luôn full width containerẢnh nhỏ bị kéo giãn (mờ, méo)
max-width: 100%Tối đa = container, tối thiểu = kích thước gốcGiữ chất lượng ảnh gốc

Responsive Image Best Practice (Hoàn chỉnh)

<img 
  src="image.jpg" 
  alt="Mô tả"
  width="800"           /* Width gốc - hint cho browser layout */
  height="600"          /* Height gốc - tránh CLS (Cumulative Layout Shift) */
  style="max-width: 100%; height: auto;"
  loading="lazy"        /* Lazy load - hiệu năng */
  decoding="async"      /* Giải mã async - không block main thread */
>

Art Direction: +

Cho phép đổi ảnh (crop, format) theo màn hình:

<picture>
  <source media="(max-width: 480px)" srcset="image-mobile.webp" type="image/webp">
  <source media="(max-width: 768px)" srcset="image-tablet.webp" type="image/webp">
  <source srcset="image-desktop.webp" type="image/webp">
  <img src="image-desktop.jpg" alt="Mô tả" width="1200" height="800" style="max-width: 100%; height: auto;">
</picture>

Responsive Images với srcset (Density switching)

<img 
  src="image-400.jpg"
  srcset="image-400.jpg 1x, image-800.jpg 2x, image-1200.jpg 3x"
  alt="Mô tả"
  style="max-width: 100%; height: auto;"
>

Container Queries (Tương lai/Gần đây)

.image-container {
  container-type: inline-size;
}
@container (max-width: 400px) {
  img { /* style cho container nhỏ */ }
}

Lưu ý

  • Luôn khai báo `width`/`height` attribute trên `` để tránh **CLS (Layout Shift)**.
  • `height: auto` tính toán tự động dựa trên tỷ lệ gốc.
  • Kết hợp `object-fit: cover` nếu cần crop ảnh vừa khung container cố định.