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

Cách làm YouTube Video Embeds Responsive với CSS

Tìm hiểu cách nhúng video YouTube trên website và làm nó responsive hoàn toàn từ mobile đến desktop, với CSS.

Nếu bạn copy embed video code từ YouTube, bạn nhận được wrapper <iframe> trông như sau:

<iframe width="560" height="315" src="https://www.youtube.com/embed/uga8GWzdv3c" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Thật đáng tiếc, iframe yêu cầu height và width cố định để hiển thị đúng tỷ lệ khung hình (aspect ratio) trên trình duyệt. Điều này làm iframe không tương thích với responsive design out of the box.

May mắn thay, bạn có thể làm video embeds responsive bằng cách wrap iframe trong parent container:

<div class="youtube-video-container"> <iframe width="560" height="315" src="https://www.youtube.com/embed/uga8GWzdv3c" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div>

Rồi style video container với CSS:

.youtube-video-container { position: relative; overflow: hidden; width: 100%; } .youtube-video-container::after { display: block; content: ""; padding-top: 56.25%; } .youtube-video-container iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

Tính toán aspect ratios

Bạn thắc mắc 56.25% padding-top là gì? Nó dựa trên aspect ratio video YouTube, là 16/9.

Để lấy giá trị padding chính xác làm video container responsive, bạn chỉ cần tìm xem height value là bao nhiêu % của width value:

9/16 * 100 = 56.25%

9 là 56.25% của 16.

Nếu aspect ratio video nhúng là 4:3, bạn tính padding-top video container như sau:

3/4 * 100 = 75%

Và cứ thế.