3

I am trying to get a HTML5 video to act exactly like a background: center center fixed; background-size: cover; element without using JS (I know there are JS libraries that do that out there). I figured out how to set the width or height to 100% depending on the aspect ratio of the window compared to the aspect ratio of the video, using media queries (the example below assumes you're using a 16/9 video). All I have left to do now is get the video to center either horizontally or vertically.

Any help would be appreciated.

@media screen and (max-aspect-ratio: 16/9) {
  div#fixed video {
    position: absolute;
    height: 100%;
    z-index: -100;
  }
}

@media screen and (min-aspect-ratio: 16/9) {
  div#fixed video {
    position: absolute;
    width: 100%;
    z-index: -100;
  }
}
1

2 Answers 2

1
@media screen and (max-aspect-ratio: 16/9) {
  div#fixed video {
    position: absolute;
    height: 100%;
    z-index: -100;
    top: 0;
    bottom: 0;
    margin:auto 0;
  }
}

@media screen and (min-aspect-ratio: 16/9) {
  div#fixed video {
    position: absolute;
    width: 100%;
    z-index: -100;
    text-align: left;
    right: 0;
    left: 0;
    margin:0 auto;
  }
}
1

You don't even need media queries to achieve that :)

Try this:

#fixed {
    position: relative;
    height: 100vh;
    z-index: 0;
}
#fixed video {
    -webkit-transform: translateX(-50%) translateY(-50%);
    -moz-transform: translateX(-50%) translateY(-50%);
    -ms-transform: translateX(-50%) translateY(-50%);
    -o-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
    position: absolute;
    top: 50%;
    left: 50%;
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    z-index: -100;
}
<div id="fixed">
	<video autoplay loop class="bg-video">
		<source src="https://d2v9y0dukr6mq2.cloudfront.net/video/preview/abstract-rainbow_wjpctkdes__PM.mp4" type="video/mp4">
	</video>
</div>

Here's a working fiddle example.

Hope it helps :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.