Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering full window video

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;
  }
}
like image 522
Rembrant Van Der Mijnsbrugge Avatar asked Mar 27 '26 01:03

Rembrant Van Der Mijnsbrugge


2 Answers

@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;
  }
}
like image 135
Lowkase Avatar answered Mar 28 '26 22:03

Lowkase


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 :)

like image 40
ala_747 Avatar answered Mar 28 '26 20:03

ala_747