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

Categories

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

html - Css background video

Does someone know how to center this video background?

I tried:

margin: 0 auto;
text-align: center;

So far but none of these worked.

This is my code.

Html:

<video autoplay loop poster="polina.jpg" id="vid">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
</video>

Css:

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

How do i center this video background so it removes on the left/right side the same amount if you resize the window? Thanks for helping!

Here is my jsfiddle: http://jsfiddle.net/pwxcvxe8/2/

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Since you are using an HTML5 element the best way to center content is to put it in a relative container and then let CSS handle the rest like this:

<div id="Container">
    <video></video>
    <div></div>
</div>

body, html {
    height: 100%;
}

#Container {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
}

#Container video {
    position: absolute;
    left: 50%;
    top: 50%;
    /* The following will size the video to fit the full container. Not necessary, just nice.*/
    min-width: 100%;
    min-height: 100%;
    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
    z-index: 0;
}

#Container div {
    position: relative;
    z-index: 1;
}

You can replace <video> by any element you want to center, of course. Because you are using the video element I'm ignoring older browsers as I guess they won't like your page anyway. You also don't have to use the min- values, and it would just center.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...