I want to set the height to match the width for all containers of the same class.
I have a number of images of various sizes across my site. I would like each image's div container to have the same height as its own width.
<div class="wrapper" style="width:600px">
<img src="image1.jpg">
</div>
<div class="wrapper" style="width:400px">
<img src="image2.jpg">
</div>
<div class="wrapper" style="width:200px">
<img src="image3.jpg">
</div>
.wrapper {
border-radius: 180px;
overflow: hidden;
}
img {
width: 100%;
}
I originally attempted the following:
$(document).ready( function() {
var wrapper = document.querySelector(".wrapper");
container.style.height = getComputedStyle(wrapper).width;
} );
This solution worked, except it only affected the first occurrence of each wrapper.
I also tried adapting another example I've found on StackOverflow (sorry can't find the link), to no avail:
$(document).ready(function() {
$('.wrapper').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > maxWidth) {
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height > maxHeight) {
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
});
});
Any help would be greatly appreciated.
JSFiddle (HTML + CSS): https://jsfiddle.net/h2xnqrL9/