Equal Height Columns with jQuery

Creating equal-height columns with CSS is sometimes a bear. But who needs the hassle of faux columns, “clear” divs and the rest? With this bit of jQuery, you can easily equalize the heights of any group of elements.

This technique was born of frustration. I ran into two layout problems while working on the redesign of CSS Newbie one afternoon, and both were directly related to the varying heights of elements.

The first problem was in the footer. If you look closely, you’ll see that there is a nice subtle two-tone border in between each of the columns in the footer.

That style wasn’t as easy to create as it might look. At first, I was going to make the border part of the background image, and just edit my content to suit. But that’s very un-web of me: the beauty of the web is we’re not constrained by sizes nearly as much as print designers.

So instead, I decided to make the borders the old-fashioned way, as legitimate CSS borders. Of course, to get it exactly the way I wanted I had to resort to a bit of a hack, matching light borders on the right side of one column with a dark border on the left side of the following column. The hack works beautifully… as long as all three of my columns are of equal height. Otherwise, the borders don’t match:

So again, I have a height-related problem. “If only there was an easy way to equalize heights without resorting to a table,” I thought thusly.

And so I set out to find an easy way. And after a bit of fiddling with jQuery, I was able to find a workable solution. Here’s the function I ended up with:

function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}
What this function is doing is:
  1. Sets a variable, “tallest,” to zero.
  2. Loops through each of the items in the group we’ve defined.
  3. If the current item is taller then the previous “tallest” item, it becomes the new tallest item.
  4. Once we’ve looked at all the items, they all get their height reset to be the same as the tallest of the group.

 
You can see it in action here.

Submit your comment

Powered by sweet Captcha