Responsive HTML Video
A video that looks perfect on your big monitor can be a disaster on a phone: it spills out of the screen, forces the page to scroll sideways, or squashes into a thin strip. People watch on phones, tablets, laptops, TVs, and everything in between, and your page must fit them all.
The good news is that making video responsive takes only a few lines of CSS. This lesson shows the ones that matter, and how to also save your visitors' data and keep the page steady while the video loads.
What You Will Learnβ
- Why a fixed-size video breaks small screens
max-width: 100%withheight: auto- The
aspect-ratioproperty, and why it prevents layout jumps object-fitandobject-position- Responsive embedded players (
iframe) - Vertical video, saving data, and lazy loading
- Common mistakes
The Problem: A Fixed Sizeβ
<video controls width="640" height="360" src="lesson.mp4"></video>
On a 1200-pixel screen, this is fine. On a 360-pixel phone, the video is 280 pixels too wide. The browser does not shrink it for you, so the page scrolls sideways, and the right part of the video is cut off.
The Fix: Let It Shrinkβ
- HTML Code
- Browser Output
<video controls width="640" height="360" src="lesson.mp4" poster="cover.jpg"></video>
video {
max-width: 100%; /* never wider than the container */
height: auto; /* keep the shape as the width changes */
}
The video is 0 px wide in a 300 px container. It fits.
video {
max-width: 100%;
height: auto;
}
In the demo, drag the container width down. With fixed size only, the video sticks out. With max-width: 100%; height: auto, it shrinks to fit and keeps its shape. The third option also fits, and sets the shape in CSS.
How it works:
width="640" height="360"(the HTML attributes) tell the browser the video's shape before it loads. The browser works out the aspect ratio from them, and reserves the right space.max-width: 100%says "never wider than the box that holds me".height: autosays "work out the height from the width, so the shape stays right". Without it, the attribute height stays at 360 while the width shrinks, and the video looks squashed.
Aspect Ratioβ
The aspect ratio is the shape: width divided by height. Common ones:
| Ratio | Shape | Used for |
|---|---|---|
16 / 9 | Wide | Most video, TV, YouTube |
4 / 3 | Slightly wide | Older video, some slides |
1 / 1 | Square | Social media posts |
9 / 16 | Tall | Phone-shot "vertical" video |
21 / 9 | Very wide | Cinema, banners |
The CSS aspect-ratio property lets you state the shape directly:
.player {
width: 100%;
aspect-ratio: 16 / 9;
}
Why It Prevents Layout Jumpsβ
While a video (or an iframe) is loading, the browser may not know how tall it will be. When it finally knows, the content below jumps down. That jump is called layout shift, and it annoys visitors and can hurt your page-quality scores.
To avoid it, give the space a shape before the content arrives, with width and height attributes, or with aspect-ratio. The browser then reserves the right amount of room immediately.
Fitting a Video into a Box: object-fitβ
Sometimes the box and the video have different shapes: a wide video in a square card, for example. object-fit decides what happens, just as it does for images:
| Value | Result | Good for |
|---|---|---|
contain | The whole video is visible, with empty bars | Anything where you must not crop, such as lessons and demos |
cover | The box is filled, and the edges are cropped | Decorative backgrounds and thumbnails |
fill | The video is stretched to the box | Almost never. It distorts the picture |
none, scale-down | Original size, or the smaller of none and contain | Rare |
object-position chooses which part to keep when cropping: center (default), left, right, top, bottom, or exact values such as 30% 20%.
Try It: Fit a Video into Different Boxesβ
Change the shape of the box and the object-fit value. With cover, change object-position too, and watch which edge of the frame is cut off.
- HTML Code
- Browser Output
<div class="card">
<video src="clip.mp4" muted autoplay loop playsinline></video>
</div>
.card {
width: 12rem;
aspect-ratio: 1 / 1;
overflow: hidden;
}
.card video {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
video {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
cover: the box is filled, and the edges of the video are cropped. Watch the left and right edges of the frame.
cover removes part of the picture. That is fine for a decorative loop, but not for a lesson where the speaker, a chart, or the captions sit at the edge. For informative video, use contain, or keep the box the same shape as the video.
Responsive Embedded Playersβ
Video from another site usually arrives in an <iframe>, which has no natural shape. It defaults to a small, fixed size. Give it a shape with aspect-ratio:
<iframe
class="embed"
title="Interview with a baker (video, 12 minutes)"
src="https://player.example.com/embed/123"
loading="lazy"
allowfullscreen></iframe>
.embed {
display: block;
width: 100%;
max-width: 48rem;
aspect-ratio: 16 / 9;
border: 0;
}
You may see an older trick on the web: a wrapper with padding-bottom: 56.25% and an absolutely placed frame. It does the same job, but it is more complex. Today, aspect-ratio is simpler and widely supported, so prefer it. Check your audience's browsers if you need to support very old ones.
Two extras for embeds:
loading="lazy"on theiframedelays loading until the visitor scrolls near it, which saves data. (It is foriframeandimg. Thevideoelement usespreloadinstead.)- Always give the
iframeatitle. See Accessible Media.
Vertical Videoβ
Videos shot on phones are often tall (9:16). On a wide desktop screen, a tall video can fill the whole height, and force a lot of scrolling.
.vertical {
width: 100%;
max-width: 22rem; /* keep it narrow on big screens */
max-height: 80vh; /* never taller than the window */
aspect-ratio: 9 / 16;
margin-inline: auto;
}
Set the shape to match the real video, not a one-size-fits-all 16:9, or you will get black bars on the sides or cropping.
Saving Data on Phonesβ
Responsive means more than size. Many mobile visitors pay for data, or have slow connections. Be kind:
- Do not preload everything. Use
preload="metadata"orpreload="none", with aposter, so nothing big downloads until the visitor presses play. - Do not autoplay video on mobile. It uses data without being asked.
- Compress the file, and do not serve a huge video to a small screen. A 4K file in a 360-pixel box is wasted data.
- Offer smaller versions when it matters. Browsers do not reliably pick a video by screen size through
sourceelements, so for large libraries, use a video service or adaptive streaming (formats such as HLS or DASH), which switches quality automatically. For a single clip, a modestly sized, well-compressed file is usually enough. - Keep the poster small: a compressed JPEG or WebP, sized for the screen.
- Choose a version with JavaScript if you need to, and check connection hints carefully. Some browsers offer
navigator.connection, but support is incomplete, so treat it as a bonus and not a rule.
const video = document.querySelector("video");
const small = window.matchMedia("(max-width: 600px)").matches;
video.src = small ? "lesson-480.mp4" : "lesson-1080.mp4";
video.preload = small ? "none" : "metadata";
Full Screen, Orientation, and Touchβ
- Add
playsinline, so video on iPhones plays inside the page instead of jumping to full screen. - Use full screen with the player's own button, or
video.requestFullscreen()from a button of your own. - Do not lock the orientation. Let visitors turn the phone.
- Keep controls large, with room for a thumb: at least 24 by 24 CSS pixels, and ideally 44.
- Keep the captions readable on a small screen. Do not set them in a tiny fixed size.
- Beware of controls drawn over the video on a narrow screen. They can cover most of the picture.
Putting It All Togetherβ
A small, solid pattern for most pages:
<figure class="media">
<video
controls
width="1280" height="720"
poster="cover.jpg"
preload="metadata"
playsinline>
<source src="lesson.webm" type="video/webm">
<source src="lesson.mp4" type="video/mp4">
<track kind="captions" src="lesson.en.vtt" srclang="en" label="English" default>
<p><a href="lesson.mp4">Download the video (MP4, 22 MB)</a></p>
</video>
<figcaption>How to build a signup form (8 minutes)</figcaption>
</figure>
.media {
margin: 0 auto 1.5rem;
max-width: 48rem; /* a comfortable reading width on large screens */
}
.media video {
display: block; /* removes the small gap that inline video leaves below */
width: 100%;
height: auto;
aspect-ratio: 16 / 9;
background: #000; /* a calm box while it loads */
}
@media print {
.media video { display: none; } /* video cannot play on paper */
}
This gives you a shape that is known before loading, a width that follows the container, a limit on very wide screens, captions, a download fallback, and a quiet print version.
Accessibility at a Glanceβ
- Never let video scroll the page sideways. Horizontal scrolling is hard for people with low vision or motor difficulties, and it can break at high zoom.
- Make sure it still works at 200 to 400% zoom, where your layout behaves like a small screen.
- Do not crop out captions, speakers, or key content with
object-fit: cover. - Keep controls and captions readable at every size.
- Keep the focus ring visible, even on small screens.
- Keep the shape consistent so people with attention difficulties are not startled by jumping content.
- Provide captions and a transcript at every screen size. See Accessible Media.
Security and Privacy Notesβ
- Responsive embeds are still third-party content. A frame can set cookies and track visitors, even before anyone presses play. Load it only after a click where you can, and ask for consent where the law requires it.
- Use
sandboxandallowattributes on iframes where the provider supports them, so the player gets only the permissions it needs. - Do not build
srcfrom untrusted input, for example a video address typed by a visitor. - Serve over HTTPS, so media is not blocked as mixed content.
- Do not reveal private details in file names such as
lesson-480-customer-name.mp4. - Choosing a version by connection or device can reveal information about the visitor. Do not send those hints to third parties without a reason and consent.
Global Audience Notesβ
- Bandwidth varies enormously. Many people use older phones and metered data. Small files,
preload="none", and a good poster make your page usable for them. - Make a text alternative available (a transcript), which loads instantly and works on any device.
- Allow translated captions and labels to be longer. Check that buttons and captions fit at small widths.
- Use logical CSS properties (
margin-inline,padding-inline) so layouts mirror correctly in right-to-left languages. - Test on real, modest phones and on a throttled connection, not just on a large monitor.
- Consider large screens and TVs too. A
max-widthstops video from stretching until it is uncomfortably huge.
Common Mistakes to Avoidβ
- Fixed
widthonly, so the video overflows on phones. max-width: 100%withoutheight: auto, so the video is squashed.- No
widthandheightoraspect-ratio, so the page jumps while loading. - Using
object-fit: fill, which stretches the picture. - Using
coveron informative video, and cropping out important parts. - Embedding an
iframewith no shape (the tiny default size). - A tall video with no
max-height, which swamps the screen on desktop. - Serving a huge file to a small screen.
- Autoplaying video on mobile.
- Forgetting
playsinline. - Leaving the inline gap below a video, by not using
display: block. - Never testing at narrow widths or at high zoom.
Practice Timeβ
Try these in your editor, with a short video or an embed code you can use:
- Add a video with
width="640" height="360", and narrow the browser. Note what breaks. - Add
max-width: 100%; height: auto;and narrow it again. - Replace the attributes with
width: 100%; aspect-ratio: 16 / 9;. - Reload with a throttled network, and check that the page does not jump.
- Put a wide video in a square box, and compare
contain,cover, andfill. - Change
object-positionwithcover, and see what is cropped. - Make an
iframeembed responsive withaspect-ratio, and give it atitle. - Add a 9:16 video, and limit it with
max-widthandmax-height. - Set
preload="none"with aposter, and check the network panel. - Bonus: zoom the page to 400%, and fix anything that scrolls sideways.
Quick Recapβ
Click a question to check your answer.
1. Which two CSS lines make a video shrink to fit its container?
max-width: 100%; stops it being wider than its container, and height: auto; keeps the shape correct as the width changes.
2. Why set width and height attributes or aspect-ratio?
They tell the browser the video's shape before it loads, so it can reserve space and the page does not jump when the video appears.
3. What does object-fit: cover do?
It fills the box and crops the video's edges to keep its shape. It is good for decorative loops, but should not be used when important content sits near the edges.
4. How do you make an embedded iframe player responsive?
Set width: 100% (with a max-width if you like) and aspect-ratio: 16 / 9 on the frame, add a title, and consider loading="lazy".
5. How can you save data for mobile visitors?
Use preload="none" or metadata with a small poster, avoid autoplay, compress the file, and use adaptive streaming or a smaller version for big libraries.
6. Why add playsinline?
On iPhones and some other mobile browsers, it keeps video playing inside the page, instead of forcing it to full screen.
Key Takeawaysβ
- Fixed-size video breaks small screens. Use
max-width: 100%; height: auto;, orwidth: 100%withaspect-ratio. - Give video and embeds a shape before they load (with
widthandheight, oraspect-ratio) to avoid layout shift. object-fitcontrols how video fits an odd-shaped box. Prefercontainfor informative video, and avoidfill.- Make
iframeembeds responsive withaspect-ratio, and give them atitle. - Limit very tall and very wide video with
max-widthandmax-height. - Save data:
preload="none"ormetadata, a smallposter, no mobile autoplay, compressed files, and adaptive streaming for large libraries. - Add
playsinline, big controls, and readable captions on small screens. - Test at narrow widths, at 400% zoom, on slow connections, and on real phones.
Congratulations, you have finished the Audio and Video section. You can now add sound and video, give browsers choices with source, attach captions and subtitles with track, build accessible controls, and make it all fit every screen. Return to the Audio and Video overview to review the lessons, or revisit Accessible Media for the full checklist.