在製作網頁時很常遇到,網站內需要嵌入 Youtube 影片,但影片無法跟隨螢幕尺寸縮放的問題。
通常使用 Youtube 分享功能嵌入的 iframe 原始碼,已經提供固定尺寸,若是拿掉寬度與高度又會跑版,這時候就需要修改 CSS,來達到影片的 RWD(響應式) 效果。
本篇文章會分享,如何利用 CSS 達到 iframe 影片自適應螢幕尺寸的方法。
步驟一取得iframe 原始碼
- <iframe width="560" height="315" src="https://www.youtube.com/embed/SORD03t7nlo" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
接著請在 iframe 的外面包一層 div(筆者命名為 videobox),利用 videobox 來控制大小縮放的比例,並清除掉多餘的 Code。
width 和 height 也一並清除,得到一個乾淨的 iframe。
- <div class="videobox">
- <iframe frameborder="0" src="https://www.youtube.com/embed/SORD03t7nlo" allowFullScreen="true">
- </iframe>
- </div>
這時候的 iframe 影片會小小一個。
步驟二
關鍵的來了!請在 CSS 的部分加入以下程式碼:
CSS
- .videobox {
- position: relative;
- width: 100%;
- height: 0;
- padding-bottom: 56.25%;
- }
- .videobox iframe {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- }
用途在於將 iframe 的寬度與高度設定 100%,並絕對定位於外層 videobox,且自適應 videobox 的大小比例做伸縮。
padding-bottom: 56.25% 為影片高度與寬度的比例 16:9 計算得來。
也就是 16 : 9 時 ➞ 9 / 16 = 56.25%
當影片是 4 : 3 時 ➞ 3 / 4 = 75%
直式影片 3 : 4 = 133%
再打開影片在大螢幕時和小螢幕時是不同的size。 |