This is a very useful snippet for ensuring that your element height (div, img etc) is always the same as the width. An example case could be a circular div that you want to ensure maintains a set aspect ratio so that it is not squashed or elongated.
There are a few examples of how to achieve this below, but we find the first the cleanest & most consistent.
|
// Best – height always same as width |
|
$(window).on("focus load resize scroll",function(){ |
|
$('.width-height').each(function() { |
|
$(this).height($(this).width()); |
|
}); |
|
|
|
// height always same as width |
|
var divWidth = $('.width-height').width(); |
|
$(window).on("focus load resize scroll",function(){ |
|
$('.width-height').css({"height": divWidth, "max-height": divWidth}); |
|
}); |
|
|
|
// height always same as width |
|
var divWidth = $('.width-height').width(); |
|
$(window).on("focus load resize scroll",function(){ |
|
$('.width-height').height(divWidth); |
|
}); |
To use the code make sure that the element has a set width value and that the element also has the appropriate class e.g. ‘.width-height’.
About the Author

Glenn
A highly experienced Web Designer / Web Developer (Webflow, WordPress, Weebly & Custom), Front-end / Back-end Developer & New Media Specialist, with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries, built up over a number of years.