Background VIDEO - Maintain Proportions

So this is the code I have used before. It could probably be tidied up a bit :sweat_smile: But it was made for a hero image. You will need to tweak it for your own use.

I ended up doing it this way, because Chrome dropped support for doing this via media queries.

Basically allows you to have a smaller video for mobile and larger video for desktop. It places a video as a background inside a div, and the padding makes the video visible.

CSS - work out the padding, by taking the video ratio and dividing (h / w). eg. 16x9 = 56.25%. My situation required a custom ratio. Bootstrap does have some standard classes such as “embed-responsive embed-responsive-16by9”. Which maybe more suitable for your use.

<style>
.embed-responsive-hero {
   margin-left: auto!important;
   margin-right: auto!important;	
}
.embed-responsive-hero::before{
   padding-top:XXXX%!important;
}
video {width: 100%;}
</style>

Code Bric

<div>
<video id="herovideo" class="embed-responsive-hero" autoplay="autoplay" muted="true" playsinline="true" loop="loop" style="background-color: #000;"  preload="auto"></video>
</div>

Script - will adjust on window resize. Again probably a better way to write this.

<!-- Select Hero Video by Screen Width -->
<script>
  var w = window.matchMedia("(max-width: 700px)");
  var vid = document.getElementById("herovideo");
  var source = document.createElement("source");
  source.id = "hvid";
  source.setAttribute("type", "video/mp4");
  vid.appendChild(source);
  
  if (w.matches) {
    vid.pause();
    source.removeAttribute("src");
    source.setAttribute("src", "YOUR MOBILE VIDEO URL HERE");
    vid.setAttribute("poster", "YOUR POSTER URL HERE");
    vid.load();
    vid.play();
  } else {
    vid.pause();
    source.removeAttribute("src");
    source.setAttribute("src", "YOUR VIDEO URL HERE");
    vid.setAttribute("poster", "YOUR POSTER URL HERE");
    vid.load();
    vid.play();
  }

window.addEventListener("resize", function(){
  var w = window.matchMedia("(max-width: 768px)");
  var vid = document.getElementById("vid");
  var source = document.getElementById("hvid");
  
  if (w.matches) {
    vid.pause();
    source.src = "YOUR MOBILE VIDEO URL HERE";
    vid.setAttribute("poster", "YOUR POSTER URL HERE");
    vid.load();
    vid.play();
  } else {
    vid.pause();
    source.src = "YOUR VIDEO URL HERE";
    vid.setAttribute("poster", "YOUR POSTER URL HERE");
    vid.load();
    vid.play();
  }
});
</script>
2 Likes