Responsive Iframe

It is common to embed videos to the websites from platforms like YouTube or Vimeo using iframes. However, ensuring that these embedded videos maintain a responsive layout can be a challenge. A responsive layout allows the video to adapt and scale properly across different devices and screen sizes.

To achieve a responsive iframe layout, you can use the following HTML and CSS code:

HTML

<div class="video-wrapper">
  <iframe src="https://www.youtube.com/embed/ScMzIvxBSi4"></iframe>
</div>

CSS

.video-wrapper {
  position: relative;
  overflow: hidden;
  width: 100%;
  padding-top: 56.25%; /* Aspect Ratio 16:9 */
}

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

In the HTML code, we wrap the iframe element inside a <div> element with the class “video-wrapper”. This wrapper is essential for maintaining the aspect ratio of the video.

The CSS code for the “video-wrapper” class is where the magic happens. By setting the position property to relative, we establish a context for the absolute positioning of the iframe inside it. The overflow property set to hidden ensures that any overflow from the iframe is clipped.

The most crucial part is setting the padding-top property of the “video-wrapper” class to a percentage value that corresponds to the desired aspect ratio. In this case, the value is 56.25%, which corresponds to a 16:9 aspect ratio. If you need any other aspect ratio, you just need to calculate the aspect ratio as a percentage: Divide the height by the width and multiply by 100 (e.g., (9/16) * 100).

By positioning the iframe absolutely with all sides set to 0, it fills the entire “video-wrapper” element. The width and height properties of the iframe are set to 100%, ensuring that it scales proportionally with the wrapper.

With this code snippet, the embedded video will adapt responsively to different screen sizes, maintaining the aspect ratio and avoiding any overflowing content.