Search code examples
htmlcssvideoiframe

Responsive iframe with fixed height


I'm trying to make an iframe with responsive width (filling a div) but fixed height (overflow hidden by div). But when I scale the page the video also scales down. I want the iframe to keep 100% height.

Does anyone know what I'm doing wrong here? I've tried not setting the iframes height, og setting it to auto, but it doesn't work.

HTML:

<div class="container">
<div class="video-wrapper">
<iframe class="video" src="https://player.vimeo.com/video/82481183?background=1" frameborder="0" allow="autoplay" ></iframe>
</div>
</div>

CSS:

.container {
background-color: green;
max-width: 1200px;
min-width: 700px;
height: 700px;
}

.video-wrapper {
background-color: red;
width: 100%;
height: 100%;
overflow: hidden;
}

.video {
height: 100%;
width: 100%;
}

https://codepen.io/marteteigen/pen/NWwdGXd

Any help is much appreciated!


Solution

  • I tried multiple ways to use CSS for this embeded player but it looks like it has to be JS with a resize listener and absolute positionning that does the job

    Codepen here to load the video: https://codepen.io/savageGoat/pen/oNoBbMz

    Full code:

    const vid = document.querySelector('.video');
    const container = document.querySelector('.video-wrapper');
    const vidWidth = vid.offsetWidth;
    const vidHeight = vid.offsetHeight;
    const applyWidthHeight = () => {
      const vidRatio = vidHeight / vidWidth;
      const parentHeight = container.offsetHeight;
      vid.height = parseInt(parentHeight) + 'px';
      vid.width = parseInt(parentHeight*vidRatio) + 'px';
      vid.style.height = parseInt(parentHeight) + 'px';
      vid.style.width = parseInt(parentHeight*vidRatio) + 'px';
    }
    
    window.addEventListener('resize', applyWidthHeight);
    document.addEventListener('DOMContentLoaded', applyWidthHeight);
    .container {
      background-color: green;
      max-width: 1200px;
      min-width: 700px;
      height: 700px;
    }
    
    .video-wrapper {
      background-color: red;
      width: 100%;
      height: 100%;
      overflow: hidden;
      position: relative;
    }
    
    .video {
      height: 100%;
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
    }
    <div class="container">
      <div class="video-wrapper">
        <iframe class="video" src="https://player.vimeo.com/video/82481183?background=1" frameborder="0" allow="autoplay" ></iframe>
      </div>
    </div>