use video as background for div
Why not fix a <video>
and use z-index:-1
to put it behind all other elements?
html, body { width:100%; height:100%; margin:0; padding:0; }
<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
<video id="video" style="width:100%; height:100%">
....
</video>
</div>
<div class='content'>
....
Demo
If you want it within a container you have to add a container element and a little more CSS
/* HTML */
<div class='vidContain'>
<div class='vid'>
<video> ... </video>
</div>
<div class='content'> ... The rest of your content ... </div>
</div>
/* CSS */
.vidContain {
width:300px; height:200px;
position:relative;
display:inline-block;
margin:10px;
}
.vid {
position: absolute;
top: 0; left:0;
width: 100%; height: 100%;
z-index: -1;
}
.content {
position:absolute;
top:0; left:0;
background: black;
color:white;
}
Demo
Pure CSS method
It is possible to center a video inside an element just like a cover
sized background-image
without JS using the object-fit
attribute or CSS Transforms
.
2021 answer: object-fit
As pointed in the comments, it is possible to achieve the same result without CSS transform
, but using object-fit
, which I think it's an even better option for the same result:
.video-container {
height: 300px;
width: 300px;
position: relative;
}
.video-container video {
width: 100%;
height: 100%;
position: absolute;
object-fit: cover;
z-index: 0;
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
Previous answer: CSS Transform
You can set a video as a background to any HTML element easily thanks to transform
CSS property.
Note that you can use the transform
technique to center vertically and horizontally any HTML element.
.video-container {
height: 300px;
width: 300px;
overflow: hidden;
position: relative;
}
.video-container video {
min-width: 100%;
min-height: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>