Ronalds Vilciņš

Make an Iframe Responsive With CSS

An iframe with a fixed width will eventually stick out of a narrow layout. Setting width: 100% fixes one half of the problem; the other half is keeping the embedded video or map at the right aspect ratio.

For a 16:9 embed, a wrapper with percentage padding does the job:

<style>
  .iframe-container {
    position: relative;
    overflow: hidden;
    padding-top: 56.25%;
  }

  .iframe-container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>

<div class="iframe-container">
  <iframe
    src="https://www.youtube.com/embed/abc123"
    title="Example video"
    allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
    allowfullscreen
  ></iframe>
</div>

The wrapper’s padding-top: 56.25% creates a 16:9 box because 9 / 16 is 0.5625. The absolutely positioned iframe fills that box as its width changes.

This older padding technique works well and does not need JavaScript. In modern CSS, aspect-ratio: 16 / 9 is clearer, but the wrapper remains useful when older browser support matters. Whichever version you use, give the iframe a useful title; responsive layout should not come at the expense of accessibility.

Enjoyed reading this?

If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.

← Back to all articles