在響應式設計中,讓嵌入影片能隨容器縮放是常見需求。HTML5 的 video 標籤可以透過 max-width: 100% 與 height: auto 保持彈性,但 iframe 或 object 內嵌影片則需要額外技巧。
video {
max-width: 100%;
height: auto;
}
可以為影片建立一個容器,利用 padding-bottom 撐出比例,再讓子元素絕對定位並填滿容器。
.video-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0;
overflow: hidden;
}
.video-container iframe,
.video-container object,
.video-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<div class="video-container">
<iframe src="https://player.vimeo.com/video/6284199?title=0&byline=0&portrait=0"
width="800" height="450" frameborder="0"></iframe>
</div>
若希望影片不要超過固定寬度,可以再包一層容器,並設定 max-width。
.video-wrapper {
width: 600px;
max-width: 100%;
}
<div class="video-wrapper">
<div class="video-container">
<iframe src="https://player.vimeo.com/video/6284199?title=0&byline=0&portrait=0"
width="800" height="450" frameborder="0"></iframe>
</div>
</div>
這個技巧可相容於 Chrome、Safari、Firefox、Internet Explorer、Opera、iPhone 與 iPad 等常見環境。