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

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

Thiết lập width: 100% cho ảnh làm cho ảnh luôn lấp đầy chiều rộng container. Khác với max-width, cách này có thể phóng to ảnh vượt quá kích thước gốc, làm giảm chất lượng.

Ví dụ: width: 100%

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    img {
      width: 100%;
      height: auto;
      display: block;
    }
  </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>

So sánh: width: 100% vs max-width: 100%

Đặc điểmwidth: 100%max-width: 100%
Container hẹp hơn ảnh gốcThu nhỏ ✓Thu nhỏ ✓
Container rộng hơn ảnh gốcPhóng to (làm mờ) ✗Giữ kích thước gốc ✓
Chất lượng ảnhCó thể giảmLuôn tối ưu
Phù hợp choBackground, banner, decorativeContent images, photos, illustrations

Khi nào dùng width: 100%?

  • Hero banner full-width
  • Background images装饰性
  • Khi ảnh gốc đủ lớn (high-res) cho mọi màn hình
  • Kết hợp object-fit: cover trong container tỷ lệ cố định

Responsive Image Pattern hoàn chỉnh

.img-responsive {
  max-width: 100%;      /* Không phóng to */
  height: auto;         /* Giữ tỷ lệ */
  display: block;       /* Loại bỏ inline gap */
  width: auto;          /* Reset width attribute */
}

/* Với aspect-ratio (modern) */
.img-responsive {
  max-width: 100%;
  height: auto;
  aspect-ratio: 16 / 9; /* Reserve space trước khi load */
}

HTML Attributes quan trọng

<img 
  src="image.jpg" 
  alt="Mô tả"
  width="800" 
  height="600"
  loading="lazy"
  decoding="async"
>

Width/height giúp browser reserve space → giảm CLS (Layout Shift).