How to: fullscreen background autoplay video on mobile in 2018
While working on the website for Corse e Strada — a client who collects vintage Ferrari cars — the client asked for a full screen video background on the homepage. Since video is well adapted online, and all browsers now support the <video> element natively, this seemed not a problem. At first.
First things first: a disclaimer. Your video should have a small footprint. Don’t do this with 1-hour length videos or 4k resolution videos. I compressed my sourcefile with handbrake to a 7 Mb (desktop) and 2,5 Mb (mobile) video file. Secondly: don’t autoplay sound (it’s annoying) and please; use this technique sparingly.
Display your video fullscreen & responsive
This can be done easily with CSS:
The .video-container is used to place the video in your website. In my code, I use absolute positioning, but you can choose to use fixed or relative positioning if needed. The overflow: hidden is important here, because it crops the excess video parts.
The <video> element itself is centered in the container (everything from line 14) and I use min-width and min-height to make sure the video fills the whole container. With this technique, the original video ratio will be kept. Depending on your screen ratio, some parts (left/right or top/bottom) will be cropped.
Use a different video for mobile or desktop
Unfortunately, there are no pure HTML solutions for responsive video. There is no srcset- or sizes-attribute we can use, like we do for images.
We have to fall back on a javascript solution.
You see what I did there? I omitted the <source> element, and added the url’s of both video-files as an attribute to the <video>-element.
The javascript logic (yes, I still use Jquery, old habits) decides which file needs to be used, and we add a <source> element with the right url to the <video>-element. We also change the width attribute (the height for the mobile & desktop video was the same in this example, so no need to dynamically change that value).
Autoplay on mobile
Safari and Chrome for mobile recently made some — much needed — changes on how video on mobile acts (webkit made it even looser, earlier you needed a user-interaction to play video). Read their policy changes here: webkit & Google. By default, it can only autoplay when the video is muted. But for webkit/iOs you also need a second attribute; playsinline. This attribute makes it so that it, well, plays inline (and doesn’t automatically jump to fullscreen video)
So, kids, that’s the story of fullscreen responsive video in 2018. Hopefully we’ll get a standardized HTML way to do this in the future.
Liked reading this article? Clap it! 👏