iFrame aspect ratio adjuster with javascript

Posted on: December 20th, 2023
By: Tadeo Martinez

It will automatically adjust the iFrame height:

<iframe width="100%" height="315" src="https://www.youtube.com/embed/RAYFCTEp7pU?si=tI7CJgqLvF91Ybdd" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

Use the following JavaScript code:

// Find all iframe elements with the class "video-container" and adjust their aspect ratio
const iframes = document.querySelectorAll('iframe');

iframes.forEach(iframe => {
  const aspectRatio = 560 / 315; // Set your desired aspect ratio here (e.g., 560/315 for 16:9)

  // Update the iframe's height to maintain the aspect ratio
  iframe.style.height = `${iframe.offsetWidth / aspectRatio}px`;

Have any questions or comments? Write them below!

Leave a Reply

Your email address will not be published. Required fields are marked *