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

Thuộc tính max-width cho video player responsive

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ínhHành viPhù hợp
max-width: 100%Thu nhỏ khi cần, không phóng to vượt video gốcVideo content, bảo toàn chất lượng
width: 100%Luôn lấp đầy container, có thể kéo giãn videoBackground 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
  • autoplay cần muted trên mobile
  • Cung cấp nhiều <source> (WebM, MP4, OGG)
  • preload="metadata" tải metadata nhanh hơn
  • poster="thumb.jpg" hiển thị ảnh chờ trước khi play