Handy jQuery Plugin for Aligning Height

Update: Folks over at css-tricks.com have a simpler solution, so I’m gonna throw in the towel on this one. Apparently if you set the height on the elements as you go, you can just check for the top position to see which element goes with which row.

Guess I should have thought of that :|

Yeah I know, just what the world needs, another jQuery plugin. Still it’s more flexible and handles more scenarios than others I’ve come across, so I guess it deserves a little write-up.

I recently worked on a dashbord-style interface for a client and needed to handle various widgets in a flexible grid. Actually more than a grid it would be endless combinations of different sized widgets as users began to customize the page – one could end up looking something like this:

Now this is easily done in CSS by floating containers of various sizes:

.col, .col_100, .col_75, .col_50, .col_33, .col_25
    margin:0 0 15px 15px;
.col_75 { width:340px; }
.col_50 { width:215px; }
.col_33 { width:131px; }
.col_25 { width:90px; }

However, as the content of each individual container grows, the rows are no longer aligned and the floats start cluttering up:

Indeed not teh roxXor and one way to handle it is to clear the floats every time there’s a full row. Depending on the design that may do just fine.

Another way is to use a piece of JavaScript to set the height of each container, to that of the max height within a given row. When working with heavy styled containers as in the above example, that is usually the best way to go.

So including the Align Height Plugin to do just that, we end up with a flexible solution that works:

When the DOM is ready you assign the plugin to the relevant containers, in this case that would be all divs with a class that begins with col..

$( document ).ready( function(){
	$( '#page > div[class^="col"]' ).alignHeight();
} );

The plugin goes through all the elements, calculate rows and align the height accordingly. To do that it needs to know what percentage of a rows total width the element corresponds to. These values are paired in the sizes object and defaults to :

// className : value
sizes: {
	'col' : 100, 
	'col_25' : 25, 
	'col_33' : 33.33, 
	'col_50' : 50, 
	'col_75' : 75, 
	'col_100' : 100 

But when applying the plugin you can easily map your own like this:

$( document ).ready( function(){
	$( '#page > div[class^="col"]' ).alignHeight( { 'col_news' : 75, 'col_feed' : 25 } );
} );

So go have a look at the full fiddle or head on over to GitHub and download the plugin:

jquery.alignheight.js ( 3.3kb )
jquery.alignheight.min.js ( 1.6kb minified with JSMin ).

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>