Sami Sami - 3 months ago 22
CSS Question

Background video with 100% width and fixed height

I need to run a video in the background. Requirements are that the video will have to run on 100% width and 600px height/max-height. Here is what i tried to do.

https://jsfiddle.net/yydkd5t4/1/

HTML

<video autoplay loop muted id="video-bg">

<source src="http://demosthenes.info/assets/videos/polina.mp4" type="video/mp4">

</video>


CSS

#video-bg {
position: fixed;
right: 0;
bottom: 0;
width: auto;
min-width: 100%;
height: auto;
min-height: 100%;
z-index: -100;
background: transparent url(video-bg.jpg) no-repeat;
background-size: cover;
}
video {display: block;}


The issue what i am facing is that when i try to fix the height it also scale down the width. Any solution to my problem will highly be appreciated.

Answer

After understanding what you are trying to achieve...

You need to add a parent div to the video. Else it will maintain the aspect-ratio and you can't achieve what you want.

#video-bg {
  position: relative;
  width: auto;
  min-width: 100%;
  height: auto;
  background: transparent url(video-bg.jpg) no-repeat;
  background-size: cover;
}
video {
  display: block;
}
.video-container {
  width: 100%;
  max-height: 600px;
  overflow: hidden;
  position: fixed;
  top: 0;
  right: 0;
  z-index: -100;
}
<!--[if lt IE 9]>
<script>
document.createElement('video');
</script>
<![endif]-->
<div class="video-container">
  <video autoplay loop muted id="video-bg">

    <source src="http://demosthenes.info/assets/videos/polina.mp4" type="video/mp4" />

  </video>
</div>

The problem with your current code or any answers till now is that it won't maintain the height: 600px because the video will always maintain his aspect-ratio.

So, you add a parent div with width: 100% and a max-height:600px with overflow:hidden. This way if the video gets a bigger height it will be hidden by the parent div.

This is probably the best way to achieve what you want, but keep in mind it will hide some parts of the video.