w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
jQuery - get tallest image's height, apply other images' height difference to top margin

Try this:

function createGrid() {
    var imgs = $('.hlist figure > img');
    var maxImgHeight = 0;

    imgs.each(function () {
        var imgHeight = $(this).outerHeight();
        maxImgHeight = maxImgHeight > imgHeight ? maxImgHeight :
imgHeight;
    });
    imgs.each(function () {
        var margin = maxImgHeight > $(this).outerHeight() ?
(maxImgHeight - $(this).outerHeight()) : 0;
        $(this).css("margin-top", (margin + "px"));
    });
}

The first each loop looks for the tallest height and stores it in maxImgHeight, as you originally had planned. The second each loop calculates and applies the margin for each image. The conditional assignment will cause the margin-top for the tallest image to be 0.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.