How to autoplay a muted video
Short answer
Add autoplay together with muted, and loop repeats the clip:
<video src="/media/flower.webm" autoplay muted loop playsinline width="320"></video>playsinline is needed for iPhone: without it the video goes fullscreen when it starts.
A video as a block background
The video is stretched over the whole block with object-fit: cover, and the text goes on top:
<style>
.hero { position: relative; isolation: isolate; display: grid; place-items: center; height: 200px; overflow: hidden; color: white; font-size: 28px; }
.hero video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; z-index: -1; }
</style>
<div class="hero">
<video src="/media/flower.webm" autoplay muted loop playsinline></video>
Spring is here
</div>Respect the user's settings
Motion on screen bothers some people. If "reduce motion" is on in the system, it is better to show a still cover (poster) — check it with the prefers-reduced-motion media query. And give a way to stop the video, for example by keeping controls.
Common mistake
Only autoplay is written, and the video does not move. Browsers forbid autoplaying clips with sound until the user has clicked something on the page. Without muted autoplay simply does not fire:
<video src="/media/flower.webm" autoplay loop width="320"></video>Functions used in this recipe
- <video> — Embeds a video in the page.
- object-fit — How the picture of an `<img>` or `<video>` fits into the element's box.
- position — How an element is positioned: in the normal flow or by offsets.