Sử dụng max-width: 100% cho thẻ <video> để video player responsive: thu nhỏ khi container hẹp, nhưng không phóng to vượt quá kích thước gốc của video.
Ví dụ: max-width cho video
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
video {
max-width: 100%;
height: auto;
display: block;
}
</style>
</head>
<body>
<video width="300" controls autoplay muted>
<source src="/html5/foo.ogg" type="video/ogg" />
<source src="/html5/foo.mp4" type="video/mp4" />
Trình duyệt không hỗ trợ video HTML5.
</video>
<p>Thay đổi kích thước trình duyệt để xem hiệu ứng responsive.</p>
</body>
</html>
max-width vs width cho video
| Thuộc tính | Hành vi | Phù hợp |
|---|---|---|
max-width: 100% | Thu nhỏ khi cần, không phóng to vượt video gốc | Video content, bảo toàn chất lượng |
width: 100% | Luôn lấp đầy container, có thể kéo giãn video | Background video, hero banner |
Aspect Ratio cho Video (Hiện đại)
.video-wrapper {
position: relative;
width: 100%;
aspect-ratio: 16 / 9;
}
.video-wrapper video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: contain; /* Giữ tỷ lệ, có thể có letterbox */
}
Cách cũ: Padding-top hack (16:9 = 56.25%)
.video-container {
position: relative;
width: 100%;
padding-top: 56.25%;
height: 0;
}
.video-container video {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
}
Responsive Video Best Practice
video {
max-width: 100%;
height: auto;
aspect-ratio: 16 / 9; /* Reserve space, tránh layout shift */
display: block;
}
/* Hoặc container query */
.video-container {
container-type: inline-size;
}
@container (max-width: 400px) {
video { border-radius: 8px; }
}
Lưu ý
- Luôn có
controlsđể user điều khiển autoplaycầnmutedtrên mobile- Cung cấp nhiều
<source>(WebM, MP4, OGG) preload="metadata"tải metadata nhanh hơnposter="thumb.jpg"hiển thị ảnh chờ trước khi play