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.

This entry was posted in javascript, prototype, work. Bookmark the permalink.

9 Responses to Equal Height Columns

  1. Tim says:

    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. Xit says:

    Wahou ! Thanks a lot !

  3. edd says:

    @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. Rick says:

    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. Tweaked to allow multiple classes to be height matched on the same page by adding each to the Event.observe call:

    function fnEqualHeightColumns(theClass)
    {
    var columns = $$(‘div.’ + theClass);
    var max_height = columns.invoke(‘getHeight’).max();
    columns.invoke(‘setStyle’, {height: (max_height + 10) + ‘px’});
    }
    Event.observe(window, ‘load’, function()
    {
    fnEqualHeightColumns(‘columnClass1′);
    fnEqualHeightColumns(‘columnClass2′);
    });

  6. wsvap says:

    THX! Very useful!
    In lot of cases you cant use css, fe. I need it to tabs (http://tetlaw.id.au/view/blog/fabtabulous-simple-tabs-using-prototype/)

  7. wsvap says:

    las1 doesnt working in IE6 :(

  8. wsvap says:

    i mean the 6.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>