Match Element Heights Using JQuery

So, you are building a design with dynamic content and the designer or client says, “but those blocks should be the same height”, and you say “but the content changes, we don’t know how tall it can be and anyway, the height needs to be different depending on what device you are using”, etc., etc.

Here is a little jQuery function you can call to set the  height of matching elements

[codesyntax lang=”javascript”]

matchHeight = function(element){
    /*keep all matching elements the height of the tallest*/
    var tallest =0
    jQuery(element).each(function(){
        el = jQuery(this);
        if( el.height()>tallest ){
            tallest = el.height();
        }
    });

    jQuery(element).each(function(){
        //jQuery(this).height(tallest); //originally I set height
        jQuery(this).css("min-height",tallest); //alternatively set min-height
    });
}

[/codesyntax]

You can then call this function when the page has loaded, and also when the window resizes (as content heights will probably change)

 

[codesyntax lang=”javascript”]

jQuery( window ).load(function() {
    matchHeight(".myblock");
});

jQuery(window).resize(function(){
    matchHeight(".myblock");
});

[/codesyntax]

 

Note: You could replace the “jQuery” with $, e.g.  $(element).each ….   if you are not using more than one JS library.

 

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Apply your human brain cells and complete this highly complicated maths problem *