Astro prevents layout shifts for <img> and <picture> by adding width and height to the generated image. Unfortunately, it does not support a similar pipeline with videos. So we are left to figure it out on our own.
Building something like this is not trivial. Not only do we have to implement the importing process that we built a couple of lessons ago, we also have to parse the video files themselves to read their dimensions.
Instead of going into the nitty-gritty details and showing you every single step of the way, I am just gonna give you the good news — I’ve built a Video component that supports videos without layout shifts!
Splendid Astro’s Video component
It’s very easy to use the Video component — you import it, point the src to the video, and you’re done!
---import { Video } from '@splendidlabz/astro'---
<Video src="..." />It outputs a video element with controls so users can choose whether to play the video.
Here’s the HTML Video creates. It contains width, height, and an aspect-ratio so the layout doesn’t shift while the video loads.
<figure> <video class="video media" playsinline controls width="800" height="450" style="width: 800px; max-width: 100%; aspect-ratio: 800 / 450;" > <source src="..." type="video/mp4" /> <a href="...">Download or watch the video directly.</a> </video></figure>Figure and caption
Video outputs figure so it’s consistent with Image. This means you can add figcaption with the caption property. You can also remove the figure wrapper by setting figure to false.
<!-- Adding captions --><Video src="..." caption="Your caption here" />
<!-- Removing the figure wrapper --><Video src="..." figure={false} />Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson