Make HTML5 video poster be the same size as video itself
To make your poster size identical to the video dimensions, assign width
and height
attributes to the <video>
tag and use an equally sized image. Below is a snapshot of the code:
Adjust the size of your poster to 320x240 pixels. In addition, apply the same CSS dimensions for style consistency.
To allow the poster to cover the animated content, we can use the object-fit
property in CSS:
Don't forget to check browser compatibility, object-fit
is not supported in some instances of Internet Explorer!
Ensuring adaptability and correct aspect ratios
How to use CSS background with a transparent image as a poster
If you prefer not to use a conventional image file for your poster, an option could be a transparent image along with a CSS background. Below is an example of how you could implement this:
You then set the poster attribute to a base64 encoded 1px transparent image. This is how it'd look:
How to effectively deal with differing browser compatibility
By using the <source>
element inside the video tag, you'd be able to offer multiple video formats for broad browser compatibility:
For browsers not fluent in object-fit
, you could consider alternative methods such as an absolutely positioned <img>
tag beneath the video.
How to fine-tune your approach for optimization and aesthetics
How to reduce the initial loading times
An effective strategy would be to use preload="none"
to stop the video from loading straight away, and consider loading the poster image lazily.
Styling your content to be responsive
For the responsive crowd, setting video dimensions to percentages would work best:
Keeping your aspect ratio consistent
Choose your poster's aspect ratio with care to either match the video's innate ratio or use object-fit: fill
to stretch the poster to fit the exact dimensions of the video.
Sifting through practical examples
Testing is a crucial part of any web developer's life. Tools such as Google Chrome's Inspector can provide real-time CSS property suggestions.
Avoid extras that may inadvertently resize the video. Below is an example of how to transparently set the video background:
For a cleaner method, you may want to embed the poster image directly in HTML with the data URI scheme:
Was this article helpful?