#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

Add a responsive fullscreen HTML5 video background to a webpage

Last modified March 18th 2021 | GitHub Source Code [GitHub] | #css #html

CSS provides a way to set a background image but currently doesn’t have support for adding a background video. Not to worry, a fullscreen background video can easily be created using the HTML5 video element & some simple CSS.

First thing to do is add a <video> element to your HTML with the following settings:

<video poster="poster.jpg" autoplay playsinline muted loop>
  <source src="myVideo.webm" type="video/webm">
  <source src="myVideo.mp4" type="video/mp4">
</video>Code language: HTML, XML (xml)

You’ll notice two different video files used here, webm is the best format for web video but isn’t currently supported by all browsers so secondary mp4 file is used as a fallback. There are many free online tools available for converting video into the required format for the web.

Let’s take a closer look at the other settings used:

  • poster – Image visible while video downloads & as a fallback on unsupported devices.
  • autoplay – Video will start playing automatically once loaded.
  • playsinline – Prevents video taking over the screen on mobile devices.
  • muted – Autoplaying video with sound is rude so we’ll ensure it’s muted.
  • loop – Once the video ends loop through continuously again from the beginning.

If you view the HTML in a browser the video should start playing at its native resolution. To achieve the fullscreen background video we just need to add the following CSS:

video {  
  width: 100vw;
  height: 100vh;
  object-fit: cover;
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
}Code language: CSS (css)

This sets the width and height of the video to 100% of the viewport and by applying a negative z-index we ensure other elements in the page will display over the video.

Now if we add another element to the HTML, for example a <h1> heading:

<h1>Hello World</h1>Code language: HTML, XML (xml)

You’ll see this text gets displayed on top of the fullscreen video in the background.

If you’re adding the video background to an exiting website the content should already be positioned correctly. For the purposes of this tutorial we can be better position the text over the video with the following CSS:

h1 {
    color: #fff;
    text-align: center;
    margin-top: 50vh;
}Code language: CSS (css)

So that’s how you add a responsive fullscreen video background to a webpage. Hopefully in the future CSS will support background video in a similar way it does background images. Until then this solution works in all modern browsers excluding Internet Explorer (which ain’t really modern anymore).

Related Posts

#AD Shop Web Developer T-Shirts