Screencast: Equalizing Column Heights with jQuery
September 16, 2009In this first screencast, I present the common problem of making the background of a floated sidebar stretch to the height of the neighboring content element and provide a simple solution using JavaScript and jQuery.
The solution uses jQuery to loop through each column on the page, find the tallest column, and set the heights of all columns to that value. Here is the script:
$(function() { var tallest = 0; var $columnsToEqualize = $(".column"); $columnsToEqualize.each(function() { var thisHeight = $(this).height(); if (thisHeight > tallest) { tallest = thisHeight; } }); $columnsToEqualize.height(tallest); });
Remember to load the jQuery library first.
Comments
September 01, 2009
I've used that trick of vertical tiling a background image to produce the background colors I want up to the full height of the page. When I do, I make the background image 10 pixels high instead of 1 pixel high because it renders faster.
Using jQuery produces a much cleaner solution. As an added bonus, your jQuery code will work for any number of columns.
October 02, 2009
I've found that when there are images in the target columns the img elements must have height attributes. Otherwise the code can't compute the correct height for the column.
How can I have the code reinvoked when a user resizes the window?
October 02, 2009
Try the resize event:
http://docs.jquery.com/Events/resize
February 10, 2010
I totally just used this code in my project at work. Sweet!
Comments are closed
Comments are automatically closed 2 weeks after publication. If you still have something to say about the article, feel free to contact me.