RWD Responsive Videos
Embedded videos like YouTube iframes don't respond to max-width the way images do, so keeping them fluid relies on a wrapper technique that locks in the aspect ratio.
Why Video Embeds Are Trickier Than Images
An embedded <iframe> ships with explicit width and height attributes, usually something like 560 by 315 pixels. Adding max-width: 100% shrinks the visible box down to fit a narrow screen, but the height attribute stays a fixed pixel number -- so as the width shrinks, the video's proportions get squashed instead of scaling evenly.
The Naive (Broken) Attempt
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<iframe
src="https://www.youtube.com/embed/dQw4w9WgXcQ"
width="560" height="315"
style="max-width: 100%;">
</iframe>
</body>
</html>The Modern Fix: aspect-ratio
The CSS aspect-ratio property lets you set width: 100% on the iframe and declare the ratio you want to maintain -- the browser then computes the matching height automatically at every viewport size. It's supported in all current evergreen browsers and needs no extra wrapper element.
Using aspect-ratio
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<iframe
src="https://www.youtube.com/embed/dQw4w9WgXcQ"
style="width: 100%; aspect-ratio: 16 / 9; border: 0;"
allowfullscreen>
</iframe>
</body>
</html>The Classic Fix: The Padding-Bottom Trick
Before aspect-ratio existed, developers achieved the same result with a clever use of a CSS quirk: percentage values for padding-bottom are calculated from the containing element's width, not its height. A wrapper div sets padding-bottom to a percentage matching the desired ratio (for 16:9, divide 9 by 16 to get 56.25%), gives itself height: 0, and then the iframe is positioned absolutely to fill that padded space completely.
Padding-Bottom Percentage Wrapper
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.video-wrapper {
position: relative;
width: 100%;
padding-bottom: 56.25%; /* 16:9 aspect ratio */
height: 0;
overflow: hidden;
}
.video-wrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
</style>
</head>
<body>
<div class="video-wrapper">
<iframe
src="https://www.youtube.com/embed/dQw4w9WgXcQ"
allowfullscreen>
</iframe>
</div>
</body>
</html>Exercise: RWD Videos
What is the standard modern technique for making an embedded video scale with its container?