CSS: Responsive iframe with aspect ratio preserved

When you want to insert an iframe, like when you embed a video from YouTube, you can wrap it and use the CSS below to make it scalable, yet preserve its aspect ratio:

.scalable {
  overflow: hidden;
}

.scalable iframe {
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

.scalable .scalable-content {
  height: 0;
  position: relative;
}

.scalable-16-9 .scalable-content {
  /* Percentage from 9 divided by 16 for ratio of 16:9. */
  padding-bottom: 56.25%;
}
<div class="scalable scalable-16-9">
  <div class="scalable-content">
    <iframe src="https://www.youtube.com/embed/BelsxknswzA"></iframe>
  </div>
</div>

Demo

Leave a Reply