Calculate Auto Aspect Ratio Automatically

1

With the example below we calculate the aspect ratio of an image by setting Width / Height manually, so the aspect ratio value is generated to be put in padding-bottom:

What I would like is something similar: I want to get the widht / height value of an image, calculate the value of the ratio, and put it in its container, all automatically. There will be several images with different dimensions.

<div class="image-container">
    <img src="minhaimagen.jpg" width="300" height="200">
</div>

The generated value would be in padding-bottom in div image-container

Example: link

For some reason you can not put the example here in the Stack.

    
asked by anonymous 08.03.2018 / 17:52

1 answer

2

You can cycle through all the images in <div class="image-container"> , calculate the ratio, and convert to % . Just divide the smaller by the largest ( width or height ) and multiply by 100 . If they are the same size, the result will be 100% .

window.onload = function(){
   
   var imgs = document.body.querySelectorAll(".image-container a img");
   
   for(var x=0; x<imgs.length; x++){
      
      var img_w = parseInt(imgs[x].getAttribute("width")),
          img_h = parseInt(imgs[x].getAttribute("height"));

          if(img_w == img_h){
             var img_p = 100;
          }else if(img_w > img_h){
             var img_p = (img_h/img_w) * 100;
          }else if(img_w < img_h){
             var img_p = (img_w/img_h) * 100;
          }
          
          imgs[x].parentNode.parentNode.style.paddingBottom = img_p.toFixed(2)+"%";
          console.log(img_p.toFixed(2)+"%");
   }
   
}
<div class="image-container">
    <a href="#">
       <img src="http://lorempixel.com/400/200"width="400" height="200">
    </a>
</div>

<div class="image-container">
    <a href="#">
       <img src="http://lorempixel.com/output/nature-q-c-300-200-1.jpg"width="300" height="200">
    </a>
</div>

<div class="image-container">
    <a href="#">
       <img src="http://lorempixel.com/output/technics-q-c-150-150-8.jpg"width="150" height="150">
    </a>
</div>

<div class="image-container">
    <a href="#">
       <img src="http://lorempixel.com/200/200/sports/"width="100" height="200">
    </a>
</div>

<div class="image-container">
    <a href="#">
       <img src="http://lorempixel.com/300/200/people/"width="300" height="200">
    </a>
</div>
    
08.03.2018 / 22:51