/

How to Create Responsive YouTube Video Embeds

How to Create Responsive YouTube Video Embeds

When embedding YouTube videos on your website, one common issue is that they are displayed as iframes which require a specific height and width. This can cause problems, especially when viewing the video on mobile devices. The key is to make the video responsive, allowing it to scale down accordingly.

To achieve a responsive YouTube video embed, follow these steps:

  1. Wrap the YouTube video in a container div:
1
2
3
<div class="video-container">
<iframe src="https://www.youtube.com/embed/...." frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
  1. Apply the following CSS to your website:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.video-container {
overflow: hidden;
position: relative;
width: 100%;
}

.video-container::after {
padding-top: 56.25%;
display: block;
content: '';
}

.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

The CSS code is responsible for making the video responsive by maintaining its aspect ratio.

The video-container class is used to set the container’s dimensions, ensuring that it takes up the full width of its parent element.

The video-container::after pseudo-element is used to create a placeholder with a percentage-based padding. In this case, 56.25% is the padding needed for a video with a 16:9 aspect ratio. If your video has a different aspect ratio, adjust this value accordingly.

The video-container iframe selector positions the iframe element absolutely within the container, filling up the available space.

By implementing the above steps, your YouTube videos will now be displayed in a responsive manner, scaling down appropriately for different devices.

Remember to adjust the padding percentage based on the aspect ratio of your video. For example, if your video has a 4:3 aspect ratio, set the padding to 75%.

Tags: responsive design, YouTube video, embedding videos, CSS, aspect ratio