pjk_ok
pjk_ok

Reputation: 947

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>

Upvotes: 0

Views: 2592

Answers (2)

Mihai T
Mihai T

Reputation: 17687

like an image, if you use width:100% and height:auto , the video takes it's original dimensions and enlarges/decreases them so that it fits the whole width, but also keep the original aspect ratio

If you want the video to stretch on height, setting also width:100% will not work because it will try to keep the original aspect ratio

Similar to using background-size:cover ( that cuts away the image so it can fill the whole wrapper but also keep the ratio ) , you can use width:auto , height:100% , together with overflow:hidden on the wrapper

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

.videoholder {
  overflow:hidden;
  height: 150vh;
  width: 50vw;
	background:url("http://lorempixel.com/1140/450/") no-repeat scroll center top /cover  #666;
}

video {
  width: auto;
  height: 100%;
}
<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>

Upvotes: 1

WizardCoder
WizardCoder

Reputation: 3461

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

Upvotes: 3

Related Questions