Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

html - center fullscreen background video

I recently played around with html5 and came across the idea to use

a fullscreen video as the websites' background using the following html-code:

<video id = "video_background" preload = "auto" autoplay = "true" loop = "loop">
  <source src = "videos/football.mp4" type = "video/mp4" />
</video> 

Additionally, I used the following css-code to align it properly:

#video_background{
    position: absolute;
    bottom: 0px;
    right: 0px;
    min-width: 100%;
    min-height: 100%;
    max-width: 4000%;
    max-height:4000%;
    width: auto;
    height: auto;
    z-index: -1000;
    overflow: hidden;
}  

It's working pretty well, but I would like to have my video horizontally centered on every browser resolution.

No matter which way I tried to achieve this effect (via margin or %-based positioning), the video kept stick to the right bottom.

Any ideas on how to resolve this "issue"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's a JQuery function I wrote a long while back to make a video a fullscreen background. Essentially if the aspect ratio of the window is taller than the aspect ratio of the video then make the height 100% and width auto and vice-versa for wider aspect ratio windows.

// Resize the video elements so that we don't get any borders due to aspect ratio
function resizeVideo() {
  if ($(window).height() > $(window).width() * 0.5425) { // Which dimension is bigger dependant on aspect ratio (16:9)
    $("video").removeAttr("height").removeAttr("width").width("auto").height("100%");
  }
  else {
    $("video").removeAttr("height").removeAttr("width").width("100%").height("auto");
  }
};


// Add the resize function to the window resize event but put it on a short timer as to not call it too often
var resizeTimer;
$(window).resize(function () {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(resizeVideo, 150);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...