Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scale different width images to fit a row and maintain equal height

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.

like image 264
Benjamin Avatar asked May 26 '15 19:05

Benjamin


1 Answers

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>
like image 169
gilly3 Avatar answered Sep 24 '22 02:09

gilly3