Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีทำ YouTube Video Embeds ให้ Responsive ด้วย CSS

เรียนรู้ embed YouTube videos บนเว็บไซต์ และทำให้ fully responsive จาก mobile ถึง desktop ด้วย CSS

Copy embed code จาก YouTube ได้ <iframe> wrapper ประมาณนี้:

<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>

เสียดายที่ iframes ต้องการ fixed height/width เพื่อ aspect ratio ถูกต้อง ทำให้ incompatible กับ responsive design out of the box

แต่แก้ได้โดย wrap iframe ใน 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>

Style video container ด้วย 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%; }

การคำนวณ Aspect Ratios

สงสัย 56.25% padding-top มาจากไหน? มาจาก aspect ratio YouTube 16/9

หา padding value สำหรับ responsive container: หาว่า height เป็นกี่ % ของ width

9/16 * 100 = 56.25%

9 คือ 56.25% ของ 16

ถ้า embedded video aspect ratio 4:3 คำนวณ top padding:

3/4 * 100 = 75%

וכןต่อไป