Ronalds Vilciņš


Responsive IFRAME

An IFRAME is an HTML element that allows you to embed another HTML document inside the current one. It is often used to embed third-party content, such as maps or videos, into a webpage. Responsive IFRAMEs are IFRAMEs that are able to adjust their size and layout to fit the size and layout of the parent container.

One way to create a responsive IFRAME is to use CSS media queries to apply different styles to the IFRAME based on the size of the viewport. For example, you can set the width of the IFRAME to 100% and the height to a fixed value in pixels when the viewport is small, and set the height to auto when the viewport is larger:

@media (max-width: 600px) {
  iframe {
    width: 100%;
    height: 250px;
  }
}
@media (min-width: 601px) {
  iframe {
    width: 100%;
    height: auto;
  }
}

You can also use JavaScript to resize the IFRAME based on the size of the parent container. Here’s an example of how you might do this:

function resizeIframe(iframe) {
  var container = iframe.parentNode;
  iframe.style.height = container.offsetHeight + 'px';
}

var iframes = document.getElementsByTagName('iframe');
for (var i = 0; i < iframes.length; i++) {
  resizeIframe(iframes[i]);
}

Here’s an example of an IFRAME that is made responsive using both CSS and JavaScript:

<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" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

<script>
  function resizeIframe(iframe) {
    var container = iframe.parentNode;
    iframe.style.height = container.offsetHeight + 'px';
  }

  var iframes = document.getElementsByTagName('iframe');
  for (var i = 0; i < iframes.length; i++) {
    resizeIframe(iframes[i]);
  }
</script>

The CSS sets the height of the container to a fixed aspect ratio (in this case, 56.25% to maintain a 16:9 aspect ratio) and the JavaScript sets the height of the IFRAME to match the height of the container. This ensures that the IFRAME is always the correct size and aspect ratio, regardless of the size of the viewport.