Equal element heights with jQuery


Even when content height differs

I often have design situations that require multiple elements that are sitting in a row to have the same height even when the content inside of them is of a different height. Sometimes I’m able to handle this in css by setting a fixed height, but other times I don’t know for certain what amount of content will be shown, and this requires me to use a little jQuery.

Take this situation for example:

uneven

The bordered containers have dynamic content, and they need to all be the same size. So with just a little jQuery, I’m able to target those containers and loop through the height of each to find the tallest one, then I can apply that height to all of them.

even

Here’s the jQuery that I use to accomplish this:

 

jQuery(document).ready(function($){
    var maxHeight = -1;

    $('.ELEMENT').each(function() {
        maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
    });

    $('.ELEMENT').each(function() {
        $(this).height(maxHeight);
    });
});// ready

A few things to keep in mind though; this would be inefficient to use on more than a handful of elements. Also if your elements contain images that don’t have a known height to apply to them, then you may end up getting a height reading in jQuery that doesn’t include the height of the images. You can delay the jQuery from running until every element on the page loads, but that could be a few seconds and cause the content to jump when the heights get set. The best option is to declare an image height in your img tags if possible.

This entry was posted in jQuery.