#AD 50 Projects In 50 Days (HTML, CSS & JavaScript) - Sharpen your skills by building 50 mini projects!
#css #html

Add a responsive fullscreen HTML5 video background to a webpage

By Michael Burrows | Last modified December 30th 2020 | GitHub Source Code [GitHub]

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> tag 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)

webm is the best format for web video but currently it isn’t supported by all browsers so mp4 is used as a fallback. There are many free online tools available for converting video formats if required.

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

  • poster – Image visible while video downloads & as a fallback on unsupported devices.
  • autoplay – Start playing the video 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. 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 is displayed on top of the fullscreen video 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.

Related Posts