RWD Videos
Embedded video usually breaks responsive layouts because <iframe> has fixed pixel dimensions. The fix is a wrapper that locks the aspect ratio.
The wrapper trick
HTML + CSS
<div class="video-wrap">
<iframe src="https://www.youtube.com/embed/…" allowfullscreen></iframe>
</div>
.video-wrap {
position: relative;
width: 100%;
aspect-ratio: 16 / 9;
}
.video-wrap iframe {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
border: 0;
}
Native <video>
HTML + CSS
<video controls poster="thumb.jpg" preload="metadata">
<source src="clip.webm" type="video/webm">
<source src="clip.mp4" type="video/mp4">
</video>
video { width: 100%; height: auto; max-width: 100%; }
Why this matters
| Property | What it does |
|---|---|
aspect-ratio: 16 / 9 | Reserves the right amount of vertical space at any width. |
inset: 0 | Modern shorthand for top: 0; right: 0; bottom: 0; left: 0; |
preload="metadata" | Don't fetch the whole video until the user presses play. |
Tip:
aspect-ratio replaced the old "padding-bottom: 56.25%" hack. Browser support is excellent — use it.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>RWD Videos</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Lock this video wrapper to 16:9.
.video-wrap { width: 100%; aspect-
: 16 / 9; }
A single word — height-to-width relationship.
Discussion
Loading…