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

Thuộc tính max-width cho ảnh responsive với CSS

Thuộc tính max-width: 100% cho phép ảnh thu nhỏ khi container hẹp hơn ảnh gốc, nhưng không bao giờ phóng to vượt quá kích thước thực tế của ảnh.

Ví dụ: max-width: 100%

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    img {
      max-width: 100%;
      height: auto;
      display: block; /* Loại bỏ gap dưới ảnh */
    }
  </style>
</head>
<body>
  <p>Thay đổi kích thước trình duyệt để xem hiệu ứng responsive.</p>
  <img src="https://www.tutorialspoint.com/python/images/python-data-science.jpg" 
       alt="Python Data Science" width="400" height="300">
</body>
</html>

max-width vs width: 100%

Thuộc tínhHành viKhi nào dùng
max-width: 100%Thu nhỏ khi container hẹp, không phóng to vượt ảnh gốcẢnh content, bảo toàn chất lượng
width: 100%Luôn lấp đầy container, có thể phóng to làm mờ ảnhBackground, decorative, full-width banner

Responsive Images Best Practice

img {
  max-width: 100%;
  height: auto;
  /* Hiện đại: aspect-ratio để tránh layout shift */
  aspect-ratio: attr(width) / attr(height);
}

/* Hoặc dùng picture element cho art direction */

  
  
  Thuộc tính max-width cho ảnh responsive với CSS

Container Queries (CSS mới)

.card-container {
  container-type: inline-size;
}
@container (max-width: 400px) {
  .card img {
    max-width: 100%;
    border-radius: 8px;
  }
}

Lưu ý

  • Luôn set height: auto để giữ tỷ lệ khung hình
  • Thêm width/height attribute trong HTML cho CLS (Cumulative Layout Shift)
  • Dùng loading="lazy" cho ảnh below-the-fold
  • object-fit: cover nếu cần crop ảnh trong khung cố định