Set Arbitrary HTML Element to 100% Width and Keep Aspect Ratio (JQuery)

You are creating another responsive layout? Well, then you will probably face the same problem like I did on my blog.

I want to embed some Youtube videos, maps and a presentation. However, they should automatically adapt to the size of the container as the layout is responsive. Browsers maintain the aspect ratio of images themselves, whereas they do not pertain the aspect ratio if you resize a div or an iframe. So you need to come up with an own solution. Mine is some simple javascript:

$( document ).ready(function() {
   $(".Map, iframe").each(function() {
      var $this = $(this);
      var ratio = $this.width()/$this.height();
      $this.css('width', '100%');
      var nh = $this.width() / ratio;
      $this.css('height', nh + 'px');
   });
});

Leave a Comment

comments powered by Disqus