How to fill video element with poster image even if the poster image is a different aspect ratio than its video element?

jonathanbell picture jonathanbell · Mar 19, 2013 · Viewed 70.2k times · Source

As it stands right now, this is only tested in WebKit.

When a poster image is set on a <video> element using the poster attribute, this image displays before the user plays the video (default behavior). However, if the poster image is of a different aspect ratio than that of the <video> element that it is set on, whitespace (or possibly blackspace) is seen on either side of the image (left and right or top and bottom) and the image is centered (also, default behavior).

I would like to know how to scale this image up (preferably in CSS) so that it fills the video element, similar to using the CSS3 background-size: cover; value.

Still confused? Perhaps this JSFiddle will help explain: http://jsfiddle.net/jonnymilano/2w2CE/

I would also be interested in answers that forced the image into the video container, warping its height and/or width to fit the dimensions of the video container. However, this answer would only partially solve my issue.

Answer

Ian Devlin picture Ian Devlin · Mar 19, 2013

This question got me thinking and your jsfiddle was useful in solving this (albeit not for IE as it doesn't implement the poster image correctly).

Basically combine what you posted, set the required poster image as the background image of the video element and specify a 2x2 transparent image as the actual poster image.

e.g.

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

and

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

I wrote a bit more about it at HTML5 Video and Background Images.