DEV Community

Cover image for Use video as background with CSS
shammisharma
shammisharma

Posted on • Edited on

Use video as background with CSS

Using images as a background is something we always do with simple css property i.e
background:url(path to image)

However, sometimes there is a need to use video as a background. In this post I will share a neat and simple trick to use video as a background.

Step 1: Create Container

First we will make a container in which video and other content will be there. Please note that height of the container will be relative to the height ratio of video. If you like you can limit it's height using (max-height) and hide overflow content with 'overflow:hidden'.

.vid-bg {width:100%; display:block; max-height: 500px; overflow:hidden;position:relative;margin:0; padding:0}
Enter fullscreen mode Exit fullscreen mode

Step 2: Set overlay content

This is the main part where we will be set our overlay content with the 'position:absolute' property. It will allow our content to remain on top of the video. Following is the code for overlay:

.vid-bg .content { width:100%; height:100%;top:0;position:absolute;background:rgba(0,0,0,0.6); padding:0px; color:#fff; text-align:center; font-size:30px; z-index:1; display:flex; align-items: center;
    justify-content: center;}
Enter fullscreen mode Exit fullscreen mode

Step 3: Use video element

Now we will use our video. There are 3 main properties that we will be using which are : 'autoplay', 'loop' & 'muted'.

  1. autoplay: It will allow us to play our video as soon as its is loaded.

  2. loop : It will allow our video to play on loop.

  3. muted : This is crucial property because without this our video will not autoplay since chromium browsers only allow muted videos to autoplay.

Keep in mind the aspect ratio of video, if you want whole video to be shown then you will have to remove the 'max-height' property else your video will be clipped.

Following is the full html & css code :
HTML:

<div class="vid-bg">
<video muted  autoplay loop width="100%" src="https://joy1.videvo.net/videvo_files/video/free/2013-08/large_watermarked/hd0992_preview.mp4">
</video>
<div class="content"><h1> Use Video as background </h1></div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.vid-bg {width:100%; display:block; max-height: 500px;  overflow:hidden;position:relative;margin:0; padding:0}

.vid-bg .content { width:100%; height:100%;top:0;position:absolute;background:rgba(0,0,0,0.6); padding:0px; color:#fff; text-align:center; font-size:30px; z-index:1; display:flex; align-items: center;
    justify-content: center;}

.vid-bg .content h1 {background: rgba(255, 255, 255, 0.5); padding:20px; color:#111; border-radius: 60px; font-size:30px; margin:0 10px;}
Enter fullscreen mode Exit fullscreen mode

TADA! You have done it. You can play around with following Codepen.

P.S. : BONUS Content in Codepen! Please check it out.

Thanks! Happy DEVing.

Top comments (0)