In this tutorial, I will show how to create Responsive Video Background using HTML and CSS? This Responsive CSS Video Background will support all the devices. You can download the full source code at the end of this post. So, Please follow the below steps.
First, we need to download some HD video which we are going to use. Here is the footage that I have in MP4 format with full HD quality (1920×1080). And also take a full screenshot of the video. This image will be used in the loadingimage attribute in the video tag which will be displayed when the video is loading.
Let’s add the video tag to our HTML page, set the loadingimage, image, and add the attributes. I want the video to start playing immediately, repeating infinite time and without any sound.
<div class="video-bg-media" aria-hidden="true">
<img src="loadingimage.jpg" alt="Video Preview">
<video autoplay loop muted playsInline src="bg.mp4"></video>
</div>
<!DOCTYPE html>
<html>
<head>
<title>Responsive CSS Video Background</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<section class=" position-relative">
<div class="video-bg-media" aria-hidden="true">
<img src="loadingimage.jpg" alt="Video Preview">
<video autoplay loop muted playsInline src="bg.mp4"></video>
</div>
<div class="cont padding-y">
<div class="flex flex-center padding-y">
<div class="text-component text-center">
<h1>Responsive Video Background</h1>
</div>
</div>
</div>
</section>
</body>
</html>
h1 {
font-size: 42px;
}
.video-bg-media {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
overflow: hidden;
}
.video-bg-media video {
position: relative;
top: 50%;
left: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
min-height: 100%;
min-width: 100%;
height: auto;
width: auto;
max-width: none;
}
.cont {
z-index: 2;
position: relative;
text-align: center;
top: 0px;
bottom: 0px;
}
.padding-y {
padding-top: 10rem;
}
.text-component {
background: rgb(0 0 0 / 42%);
color: #fff;
padding: 20px 60px;
}
.flex-center {
justify-content: center;
align-items: center;
}
.flex {
display: flex;
}
@supports ((-o-object-fit: cover) or (object-fit: cover)) {
.video-bg-media video {
-o-object-fit: cover;
object-fit: cover;
height: 100%;
width: 100%;
}
}
@supports ((-o-object-fit: cover) or (object-fit: cover)) and (-ms-ime-align: auto) {
.video-bg-media video {
height: auto;
width: auto;
}
}
.video-bg-media img {
display: none;
}
@media (prefers-reduced-motion: reduce) {
.video-bg-media video {
visibility: hidden
}
.video-bg-media img {
display: block;
position: absolute;
-o-object-fit: cover;
object-fit: cover;
height: 100%;
width: 100%
}
}