Để hình ảnh nền (background-image) responsive, sử dụng background-size: contain hoặc cover kết hợp background-repeat: no-repeat và background-position: center.
Ví dụ: background-size: contain
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.hero {
width: 100%;
height: 300px;
border: 2px dashed #3498db;
background-image: url('https://www.tutorialspoint.com/python/images/python-data-science.jpg');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
}
</style>
</head>
<body>
<p>Thay đổi kích thước trình duyệt để xem hiệu ứng responsive.</p>
<div class="hero"></div>
</body>
</html>
So sánh contain vs cover
| Giá trị | Hành vi | Use case |
|---|---|---|
contain | Hiển thị toàn bộ ảnh, giữ tỷ lệ, có thể có khoảng trống | Logo, illustration, product image |
cover | Lấp đầy toàn bộ container, giữ tỷ lệ, có thể bị cắt | Hero banner, full-screen background |
100% 100% | Kéo giãn méo ảnh để lấp đầy | Ít dùng (làm méo ảnh) |
Responsive Hero Section (Best Practice)
.hero {
min-height: 100vh;
background-image: url('hero.jpg');
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed; /* Parallax effect */
display: flex;
align-items: center;
justify-content: center;
text-align: center;
color: white;
}
@media (max-width: 768px) {
.hero {
background-attachment: scroll; /* Tắt fixed trên mobile */
min-height: 60vh;
}
}
Multiple Backgrounds Responsive
.multi-bg {
background-image:
url('pattern.png'),
url('hero.jpg');
background-repeat: repeat, no-repeat;
background-size: auto, cover;
background-position: 0 0, center center;
}
Art Direction với <picture> (HTML) - Tốt hơn CSS
<picture>
<source media="(max-width: 480px)" srcset="hero-mobile.jpg">
<source media="(max-width: 1024px)" srcset="hero-tablet.jpg">
<img src="hero-desktop.jpg" alt="Hero">
</picture>
Ưu điểm: Tải ảnh phù hợp kích thước, tiết kiệm bandwidth.