使iframe响应媒体查询

时间:2018-07-19 16:09:09

标签: html css responsive-design

我正在一个项目中在同一div容器中同时显示html5和iframe。此代码的预期用途是在我们的主页上针对移动和台式机版本显示自动播放视频。该块的尺寸小于桌面设备上的375px,并且由于移动设备的限制,我们无法显示html5自动播放视频,因此我们将包含带有视频链接的iframe,移动块大于375px

我可以在测试中使用媒体查询,但是我无法弄清楚如何使iframe位置响应位置相对和绝对方法

<style>
@media only screen and (min-width: 375px) {
#iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#iframe {
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
 }
#video {
display: none;
}}
@media only screen and (max-width: 375px) {
#video {
 display: block;  
 }
#iframe {
 display: none;
 }
}
</style>

HTML:

<div class="item white">
<div id="iframe">
<iframe  src="https://player.vimeo.com/video/279740359" 
 width="320" height="240" frameborder="0" allowfullscreen="" >Browser 
 not compatible.
</iframe>
</div>
<div id="video"> 
<a href="https://www.shopbentley.com/en/back-to-school.html"> 
<video  width="100%" height="100%" loop autoplay muted 
 preload="metadata"><source 
src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4" type="video/mp4" />      
 Your browser does not support the video tag. I suggest you upgrade 
 your browser.
</video> 
</a> 

链接到工作代码http://jsfiddle.net/fe3vd2ts/12/

1 个答案:

答案 0 :(得分:0)

我只需要修复选择器和容器:D

<style>
@media only screen and (max-width: 375px){

 .wrapper-with-intrinsic-ratio {
    position: relative;
    padding-bottom: 56.25%;
 }

.element-to-stretch iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;

 }
 .video {
 display: none;  
 }
 }
 @media only screen and (min-width: 375px){
.video{display: block;}
.wrapper-with-intrinsic-ratio{display: none;}} 
</style>

HTML:

 <div class="item white">
 <div class="wrapper-with-intrinsic-ratio">
    <div class="element-to-stretch">
        <iframe  src="https://player.vimeo.com/video/279740359" width="100%" 
         height="100%" frameborder="0" allowfullscreen="" >Browser not 
         compatible.
        </iframe>
    </div>
</div>
<div class="video"> 
    <a href="https://www.shopbentley.com/en/back-to-school.html"> 
        <video  width="100%" height="100%" loop autoplay muted 
         preload="metadata"><source src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4"
 type="video/mp4"/>      

    Your browser does not support the video tag. I suggest you upgrade your 
     browser.
    </video> 
    </a>
    </div> 
</div>