HTML5 Video and Background Images

Stack Overflow can be a great place to get the mind going and this evening was no exception. A question was posted asking how to get a HTML5 video’s poster image to fill the element if its aspect ration differs.

Firt off, let’s take a piece of straightforward code for embedding a video in a page:

<video controls>
   <source src="parrots.mp4" type="video/mp4">
   <source src="parrots.webm" type="video/webm">
</video>

This particular video shows some colourful parrots, so we would like to have a poster image indicating some colourful parrots, which we usually add using the poster attribute:

<video controls poster="parrots.jpg">
   <source src="parrots.mp4" type="video/mp4">
   <source src="parrots.webm" type="video/webm">
</video>

But this poster image doesn’t quite fit in the video as it’s a different aspect ratio to the video itself.

So what can we do?

The answer is actually quite simple. Instead of providing our poster image as a value to the poster attribute, we define it as a background image for our video element, and use the background-size property to tell the browser that the image is to cover the element in question:

video {
   width:305px;
   height:160px; 
   background:transparent url('parrots.jpg') no-repeat 0 0;
   -webkit-background-size:cover;
   -moz-background-size:cover;
   -o-background-size:cover;
   background-size:cover;
}

(the width and height need to be specified for Opera)

We now take a 2×2 transparent image and set that to be the poster image of the video element:

<video controls poster="transparent.png">
   <source src="parrots.mp4" type="video/mp4">
   <source src="parrots.webm" type="video/webm">
</video>

And that’s it. Our background image now fully covers the video element as required. I’ve put together an example so you can see it in action.

Unfortunately, due to Internet Explorer not implementing the poster attribute correctly as defined by the specification, this method doesn’t work in either IE9 or IE10.

It also has the added bonus of displaying the image (albeit not stretched) for browsers that don’t support the video element.