My mobile-first slider features three different types of images: tall, horizontally long, and square. I want the size of the slider to be determined by the horizontally long image and then scale and center the other images to fit its size. To achieve this, I used CSS code with width:100%; height:auto;
so that all images are loaded with the same width (100%) but varying heights. I then implemented JavaScript to calculate the height of the image with the maximum width/height ratio and set it as the height for all images. Finally, I used width:auto; height:100%;
to ensure that all images fit the calculated height.
The HTML structure for each slide includes the following:
<div class="img">
<img src="" alt="">
</div>
Here is my CSS code:
.img{
position: relative;
vertical-align: middle;
}
.img img{
width: 100%;
height: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
And here is the JavaScript code:
$(".img img").width = "100%";
$(".img img").height = "auto";;
var img_h , Imgs_heights=[], ratio=[];
slider.item.find(".img img").each(function(){
Imgs_heights.push($(this).height());
ratio.push($(this).width()/(($(this).height())));
});
img_h = Math.max.apply(Math,ratio);
var i = r.indexOf(img_h );
$(".img").height(Imgs_heights[i]);
$(".img img").css("height", "100%");
$(".img img").css("width", "auto");
While everything works well initially, I encounter an issue when resizing the window. The height of the images does not change dynamically upon resize and requires a page refresh to display the desired result. I tried adding extra lines in the JavaScript to enforce width:100%; height:auto;
on resize, but it did not resolve the problem.
Any assistance in resolving this issue would be greatly appreciated.