notebook

from edd couchman, the creator of redheat and chopter

Equal Height Columns

There are no CSS hacks that can get equal-sized columns, so I wrote this tiny bit of Javascript to do the work for you. Simply add a class of “column” to any <div>s and their heights will match when the page loads.


function matchColumns()
{
var columns = $A($$('div.column'));
var column_height = 0;
var max_height = 0;
columns.each(function(column)
{
column_height = column.getHeight();
max_height = ( column_height > max_height ) ? column_height : max_height;
});

columns.each(function(column)
{
column.setStyle({
height: (max_height + 10) + 'px'
});
});
}

Event.observe(window, 'load', matchColumns);

As always, this script requires prototype, and will work better if you have a DOMReady function instead of window.load.


Categorized as javascript, prototype, work

5 Comments

  1. Even easier with Prototype 1.6:
    function matchColumns()
    {
    var columns = $$(’div.column’);
    var max_height = columns.invoke(’getHeight’).max();
    columns.invoke(’setStyle’, {height: (max_height + 10) + ‘px’});
    }

  2. Wahou ! Thanks a lot !

  3. @Tim, it’s even easier to do the following:
    var columns = $$(’div.column’),
    height = columns.inject(0, function (acc, el) {
    var h = el.getHeight();
    return (h > acc) ? h : acc;
    }
    columns.invoke(’setStyle’, { height: height + ‘px’ });

  4. I just need a simple explanation of what the code surrounding the function should be. I have:

    Also I’ve placed prototype.js in my main directory, but don’t know exactly what needs to be done to install that.

    Thanks,
    Rick

  5. Why use JavaScript when equal height columns with cross-browser CSS is possible?

Leave a Reply