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ính
Hành vi
Khi 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ờ ảnh
Background, 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 */