iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

PropertyWhat it does
aspect-ratio: 16 / 9Reserves the right amount of vertical space at any width.
inset: 0Modern 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 &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Lock this video wrapper to 16:9.

.video-wrap { width: 100%; aspect- : 16 / 9; }

Test yourself

Q1. Which property locks an embed to 16:9 without padding hacks?
Q2. Which CSS shorthand sets top/right/bottom/left to 0?
Q3. Why use `preload="metadata"` on `<video>`?

Discussion

Loading…