scale HTML5 Video and break aspect ratio to fill whole site

Viewed 111349

I want to use a 4:3 video as a background on a site. However, setting the width and height to 100% doesn't work since the aspect ratio is kept intact, so the video doesn't fill the whole width of the site.

Here is my HTML and CSS code.

HTML:

<!DOCTYPE HTML>
<html land="en">

<head>

<link rel="stylesheet" type="text/css" href="html5video.css" />


<title>html 5 video test</title>


</head>

<body id="index">

<video id="vidtest" autoplay>
<source src="data/comp.ogv" type="video/ogg" width="auto" >
</video>

<div class="cv">

<p>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>

</div>


</body>
</html>

CSS:

body
{
background-color:#000000;
}



#vidtest {
position: fixed;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
width: 200%;
height: 100%;
z-index: -1000;
}

.cv
{
width: 800px;
position:relative;
text-align:center;
margin-top: 100px;
color:#FFFFFF;
font-family:"Arial";
font-size: 10px;
line-height: 2em;
text-shadow: 3px 3px 2px #383838;
margin-left: auto;
margin-right: auto;
}
9 Answers

If the object-fit property is not working for you (WebView, Android, etc.), you can calculate the height of your video yourself.

For example, for video 16:9 the height is calc(100vw * 9 / 16)

.video-wrapper {
    width: 100%;
    height: calc(100vw * 9 / 16);
    position: relative;
}

video {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

After some struggling, this is what I ended up with. It will automatically scale the video in the right moment.

var videoTag = $('video').get(0);
videoTag.addEventListener("loadedmetadata", function(event) {
   videoRatio = videoTag.videoWidth / videoTag.videoHeight;
   targetRatio = $(videoTag).width() / $(videoTag).height();
    if (videoRatio < targetRatio) {
      $(videoTag).css("transform", "scaleX(" + (targetRatio / videoRatio) + ")");
    } else if (targetRatio < videoRatio) {
      $(videoTag).css("transform", "scaleY(" + (videoRatio / targetRatio) + ")");
    } else {
      $(videoTag).css("transform", "");
    }
});

Just put that code in a $(document).ready() block.

Tested on Chrome 53 , Firefox 49, Safari 9, IE 11 (IE does scale the video correctly, but might do other funny stuff around it though).

Related