網頁插入影片、HTML 5 Canvas 內嵌到網站,使用 iframe 標籤,如果設定寬度和高度為 100% 或 Auto 是無法做到隨網頁大小自動縮放效果的,這時必須透過一個 Div 容器來自動調整寬度和高度了。
當我們需要分享 Youtube、抖音Tik Tok、土豆的影片,就可以在 RWD 網頁中顯示的大小,隨著視窗大小,自動放大、縮小 iFrame 的內容,大家可以使用下面方法,此法對於 iframe 的相關物件皆有效果。
此法原理是使用 .youtube 裡的 padding-bottom 屬性將 iframe 撐開,這裡使用 56.25% 是因為 iframe 起始值的 width 為 560 而 height 為 315,所以 height 永遠為 width 的 56.25 ,因此得到 56.25%。
CSS:
.iframe-auto {
overflow: hidden;
position: relative;
padding-bottom: 100%; /* This is the aspect ratio */
}
.iframe-auto iframe {
top: 0;
left: 0;
width: 100%;
height: 100%;
position: absolute;
}
Html:
<div class="iframe-auto"><iframe src="" frameborder="0" scrolling="no" allowtransparency="true" allowfullscreen="true"></iframe></div>
備註:請自行調整 padding-bottom 比例
如: 影片建議高度為 padding-bottom: 56.25%
如: 調用 Canvas 標籤 或 物件 不用修改代碼
如: 想修改「寬度和高度」只要在 <div class="iframe-auto"> 標籤,改為 <div class="iframe-auto" style="padding-bottom:95%;"> 其中 95% 請自行調整。
代碼測試︰ ifreesite.com/runcode.htm
技術文檔: