CSS保健室|如何嵌入響應式YouTube影片?


Posted by itiswonderfall on 2022-06-25

前言

現在網頁基本上都要求是 RWD 響應式,可是在嵌入 YouTube 影片後,不論怎麼改變視窗大小,影片就是不會一起變化( 覺得很像在瀑布下修行的人,心無旁騖呀~ ),那要怎麼樣才能讓視窗在縮放的時候,影片也能等比例調整呢?

圖片來源

 


 

只需要 HTML 跟 CSS 就可以達成

HTML

在 iframe 的外層包一個 class 名稱為 video-container 的 DIV

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

CSS

下面的 56.25% 是依照 16:9 的比例去換算的 -> (100% × 9) ÷ 16
如果你影片寬高比例不同可以自行調整數值。

.video-container {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    height: 0;
}
.video-container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

 

偷渡我最近腦海一直出現的歌哈哈哈

 


 

資料來源

Automatic height when embedding a YouTube video?


#css #css保健室 #響應式 #RWD #iframe #youtube







Related Posts

DAY23:Build a pile of Cubes

DAY23:Build a pile of Cubes

[Day 01] 單例模式及簡單工廠設計模式

[Day 01] 單例模式及簡單工廠設計模式

JS-[非同步篇]-非同步 | Ajax  | APIs

JS-[非同步篇]-非同步 | Ajax | APIs


Comments