Search code examples
htmlcssvideoalignment

Make a Video Match the size of its Parent Container (which uses vh and vw units)


I have a video element within a container, and I'd like it so that it fills the said parent container (the equivalent of background-size: cover; that is used for background images). The parent container of the video uses vw and vh units.

I'm really struggling. I can get it so it fits the width just by using width: 100%, but height: auto doesn't fill the height of the container and using the same vw and vh measurements as the parent element is also unsuccessful.

How would i approach this - I seem to be go around in circles / pulling my hair out.

Is this going to need a JS solution?

Any ideas would be awesome. Code and Codepen link are below.

codepen: https://codepen.io/pauljohnknight/pen/EXwbzz

var video = document.getElementsByTagName('video');
video[0].play();
video[0].loop = true;
video[0].controls = false;
* {
  margin: 0;
  padding: 0;
}

.videoholder {
  background: #666;
  height: 150vh;
  width: 50vw;
}

video {
  width: 100%;
  height: auto;
}
<div class="wrapper">
  <div class="videoholder">
    <video src="https://www.marketing-people.com/wp-content/uploads/2017/02/bakerbox-mockup.mp4" class="myvideo"></video>
  </div>
</div>


Solution

  • You can absolute position the video tag to fill the parent container and then use object-fit: cover; on the video tag.

    https://codepen.io/anon/pen/Xgexdj

    Update: This will not work in any version of IE. This is a polyfill that will get it working in IE 8 - 11. https://github.com/jonathantneal/fitie