Categories
WordPress

Resize iframes (for video) maintainig the aspect ratio

Ok, so you have pages with iframes, maybe the old one from Youtube:

<iframe src="..." width="500" height="400"></iframe>

but you want to force them to be 100% width:

iframe {
  width: 100%;
  max-width: 100%
}

and the height won’t be correct. You can use FitVid.js or a piece of code like this one:

document.addEventListener("DOMContentLoaded", function () {
  let fs = document.getElementsByTagName('iframe');
  for (let i = 0; i < fs.length; i++) {
    let f = fs[i];
    if (f.width && f.height) {
      f.style.height = f.height / f.width * f.offsetWidth + 'px';
    }
  }
});

Leave a Reply