</> Michael Burrows

Add a fullscreen HTML5 video background to a webpage

Last modified on September 14th 2020 GitHub [Source] CodePen [Demo]

CSS allows us to set a background image but currently doesn’t have support for background video.

Not to worry, setting a fullscreen background video can easily be created with some simple HTML & CSS.

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

<video poster="screenshot.jpg" autoplay playsinline muted loop> <source src="myVideo.webm" type="video/webm"> <source src="myVideo.mp4" type="video/mp4"> </video>

webm is the best format for web video but it isn’t supported by all browsers so mp4 is used as a fallback.

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

  • poster – Image to display while the video is downloading & as a fallback for unsupported devices.
  • autoplay – Start playing the video automatically once loaded.
  • playsinline – Prevents the default fullscreen behavior that obscures content on mobile devices.
  • muted – Would be rude to have an autoplaying video with sound 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; }

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

<h1>Hello World</h1>

It can be positioned over the video with the following CSS:

h1 { color: #fff; text-align: center; margin-top: 50vh; }