Calculating dynamic height using aspect ratio

Posted By : Arun Kumar | 30-Jun-2016

To calculate new width to be assigned to an element, first we need to calculate the aspect ratio or the given element or an image.

So, let's discuss the formula to calculate the aspect ratio :

aspect ratio = original height / original width

The aspect ratio can be calculated by dividing original height by original width.

To calculate and set new height of the element ,we will also need to calculate the width of the screen.

let's modifiy our formula to calculate the new height.

aspect ratio x new width  = new height.

 

example.:

 

To get this working let's suppose we have an element with class "target".

 

Now, lets jquery to get and set the new heigh of the target element according to the new width.

 

Let's start with document ready event.

 

$(document).ready(function(){

   var aspectRatio = $('.target').width() / $('.target').height();

    var newHeight = aspectRatio x $(window).width();

    $('.target').height(newHeight);

});

This will set the new height to the "target" element after calculating the new aspect ratio.

Thanks for reading this.

 

About Author

Author Image
Arun Kumar

Arun is a creative UI Developer

Request for Proposal

Name is required

Comment is required

Sending message..