How to create a HTML5 background video using HTML, CSS and JavaScript


HTML – remove the poster attribute and add a class telling it to fade in:

<video class="fade-in-video" autoplay loop muted>

CSS – add the poster as a background image instead, and styles for the opacity classes:

.video-bg {
    background: url(path/to/poster.jpg) center center no-repeat;
    background-size: cover; /* Should be run through an auto-prefixer */
.fade-in-video {
    opacity: 0;
    transition: opacity .8s linear;
} {
    opacity: 1;  

JavaScript – add the .is-playing class when the video starts:

var fade_in_videos = document.querySelectorAll('.fade-in-video');
for( i=0; i<fade_in_videos.length; i++ ) {
    fade_in_videos[i].addEventListener("playing", function(){
        this.className += ' is-playing';

This JavaScript allows for multiple background videos on your page, and should be placed after all your video tags, or if you’re using jQuery, inside $(document).ready().