How to Embed a YouTube Video Responsive While Keeping the Aspect Ratio

Dr. Adam Nielsen
3 min readOct 2, 2024

--

Embedding videos on a website is essential for sharing content, but one common challenge is making the video responsive. If the video doesn’t scale properly, it might either extend beyond the screen on smaller devices, or appear squashed and thin. In this blog post, we’ll walk through how to make a YouTube video responsive while keeping its aspect ratio, and explain why some solutions fail without a wrapper.

The Issue with Fixed Widths and Full-Width Videos

When embedding a YouTube video, you might initially set a fixed width (like 560px by 315px for a 16:9 aspect ratio). However, while this works well on larger screens, on mobile devices, the video can overflow and cause horizontal scrolling. This is a poor user experience as it requires visitors to scroll horizontally to view the entire video.

Even worse, when you scroll to the left, you see a gap for the other images:

To resolve this, you might think to use width: 100%, allowing the video to fill the screen. However, without proper height adjustments, the video can become too thin and distorted, losing its original aspect ratio, or is not shown, when auto height is reduced to 0.

The Key: Using a Wrapper to Maintain Aspect Ratio

To keep the video responsive while maintaining its aspect ratio, the best approach is to use a wrapper with padding. The padding helps ensure that the height of the video scales proportionally with the width, preserving the correct 16:9 ratio.

Here’s how to do it:

Step 1: HTML Structure

<div style="position: relative; width: 100%; padding-bottom: 56.25%; height: 0;">
<iframe src="https://www.youtube.com/embed/JzcbSpNbhOI?si=jiUiN_nyOmpNropx" frameborder="0" allowfullscreen
style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe>
</div>

Step 2: How It Works

  1. Wrapper with padding: The div around the iframe acts as a responsive container. We set padding-bottom: 56.25%, which corresponds to a 16:9 aspect ratio (9 ÷ 16 = 0.5625, so 56.25%). This technique allows the div to scale the video’s height in proportion to its width.
  2. Relative positioning: The wrapper is given position: relative to ensure the iframe is positioned relative to this container.
  3. Absolute iframe: The iframe itself is positioned absolutely (position: absolute) inside the wrapper, taking up the full width and height of the container (width: 100%; height: 100%). This ensures that the iframe resizes proportionally within its container.

By using this method, the video will always adjust to the screen size while maintaining its aspect ratio.

Example of a properly responsive video with the correct aspect ratio:

--

--

Dr. Adam Nielsen
Dr. Adam Nielsen

Written by Dr. Adam Nielsen

PHD in math. and Laravel / Vue Full-Stack-Developer

No responses yet