I have three images which are all different widths, but each the same height.
I want these images to be in a responsive row so that the combined width of these three images is 100% the width of the screen, all of the images have equal height, each image maintains its aspect ratio, and the images are not cropped.
One way to do it would be to set a different percentage width for each image in CSS, based upon each image's width according to the others. But I'm curious about a smarter way, probably using JavaScript/jQuery, which would be more efficient for doing this type of thing at a larger scale.
If the source images vary in height, you will have to use JavaScript. Set all of the images to an arbitrary common height and find their combined width at that height. Then increase the height by multiplying the difference of the target width and the combined width (as a percentage):
$(window).on("load resize", function () { // wait for the images to complete loading
$(".imgRow").each(function () {
var row = $(this);
var imgs = row.find("img");
imgs.height(1000);
var combinedWidth = imgs.get().reduce(function(sum, img) {
return sum + img.clientWidth;
}, 0);
var diff = row.width() / combinedWidth;
imgs.height(999 * diff); // 999 allows 1 px of wiggle room, in case it's too wide
});
});
.imgRow {
clear: left;
}
.imgRow img {
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imgRow">
<img src="//www.placecage.com/100/300" />
<img src="//www.placecage.com/300/300" />
<img src="//www.placecage.com/500/300" />
</div>
<div class="imgRow">
<img src="//www.fillmurray.com/600/300" />
<img src="//www.fillmurray.com/200/300" />
<img src="//www.fillmurray.com/400/300" />
</div>
<div class="imgRow">
<img src="//www.stevensegallery.com/500/300" />
<img src="//www.stevensegallery.com/100/300" />
<img src="//www.stevensegallery.com/300/300" />
</div>
<div class="imgRow">
<img src="//www.placecage.com/400/300" />
<img src="//www.placecage.com/600/300" />
<img src="//www.placecage.com/250/300" />
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With