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

前端 未结 5 870
一向
一向 2021-02-03 10:09

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

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-03 10:49

    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;
    }
    
    

提交回复
热议问题