Để video player tự thích ứng chiều rộng container (responsive), thiết lập width: 100% và height: auto cho thẻ <video>.
Ví dụ: Video responsive cơ bản
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
video {
width: 100%;
height: auto;
max-width: 100%; /* Đảm bảo không tràn */
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>
Tỷ lệ khung hình (Aspect Ratio) - Cách hiện đại
Vấn đề: height: auto không hoạt động tốt cho video nếu metadata chưa load. Dùng aspect-ratio:
.video-wrapper {
position: relative;
width: 100%;
aspect-ratio: 16 / 9; /* Tỷ lệ 16:9 */
}
.video-wrapper video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: contain; /* Hoặc cover */
}
Cách cũ: Padding-top hack (Aspect ratio box)
.video-container {
position: relative;
width: 100%;
padding-top: 56.25%; /* 16:9 = 9/16 = 56.25% */
height: 0;
}
.video-container video {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
}
Responsive với max-width giới hạn
.video-responsive {
width: 100%;
max-width: 800px; /* Không lớn hơn 800px */
height: auto;
margin: 0 auto; /* Căn giữa */
display: block;
}
Lưu ý
- Luôn thêm
controlsđể user điều khiển autoplaycầnmutedtrên mobile- Cung cấp nhiều
<source>cho cross-browser - Dùng
postercho thumbnail trước khi play