Post

Responsive Youtube Video CSS

To embed a responsive YouTube video in HTML and apply CSS for responsiveness, you can use the following code. This code will ensure that the video adjusts to the width of its container while maintaining its aspect ratio:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Container for the video */
.video-container {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 aspect ratio (9 / 16 * 100%) */
  padding-top: 30px;
  height: 0;
  overflow: hidden;
}

/* Responsive iframe */
.video-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
1
2
3
4
5
6
7
8
9
<div class="video-container">
  <iframe
    width="560"
    height="315"
    src="https://www.youtube.com/embed/VIDEO_ID"
    frameborder="0"
    allowfullscreen
  ></iframe>
</div>

In this code:

1
2
3
4
5
The video-container div acts as a wrapper for the embedded YouTube video.
The padding-bottom property is set to 56.25% to maintain a 16:9 aspect ratio. You can adjust this value if you want a different aspect ratio.
The padding-top and height properties are set to ensure the container has the correct height to maintain the aspect ratio.
The overflow: hidden property hides any content that overflows the container.
The iframe inside the container takes up 100% of the container's width and height, making the video responsive.

You’ll need to replace “https://www.youtube.com/embed/VIDEO_ID” with the actual YouTube video URL or embed code for the video you want to display. This code will ensure that the video resizes proportionally to the width of its container, making it responsive on different screen sizes.

restrict width

if you want to restrict the width of the video you will need to add a container to the html markup and apply amax-width to that.

1
2
3
4
5
<div class="wrapper">
  <div class="video-container">
    <iframe></iframe>
  </div>
</div>
1
2
3
4
.wrapper {
  margin: 0 auto;
  max-width: rem(807px);
}
This post is licensed under CC BY 4.0 by the author.