DEV Community

Michael Burrows
Michael Burrows

Posted on • Updated on • Originally published at

Add a fullscreen HTML5 video background to a webpage

*** Working demo on CodePen.

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">
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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

<h1>Hello World</h1>
Enter fullscreen mode Exit fullscreen mode

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

h1 {
    color: #fff;
    text-align: center;
    margin-top: 50vh;
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

kanghadijoe profile image
Hadi Pribadi

Nice article, i trying implement the code and its work but i have no idea how to make smooth looping the video, can you give a hints? :)