Jimmy Cuadra Web Services

RSS Screencast

Equalizing Column Heights with jQuery

In 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.

View the screencast in high definition View the screencast in high definition

View the screencast on YouTube View the screencast on YouTube

Screencast notes Notes

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.

The full file from the screencast is available here.



Tagged with: new features, jquery, javascript, css

View all screencasts

Comments

Kneel commented

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.

Kneel commented

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?

Jimmy commented

Try the resize event:

http://docs.jquery.com/Events/resize

Nebyoolae commented

I totally just used this code in my project at work. Sweet!

Add a comment

Optional fields are denoted in italics.

Find content by tags