« Finally, access the Android Market via desktop or web | Main | Manual Droid 2.1 update works great »

Matching div heights automatically

Nothing is as much of a pain as having two colors divs sitting side by side that look great in one browser but have different heights in another browser. This can happen with callout boxes in the content of a page, or more commonly with a left- or right-hand sidebar that isn't the same height as the content column. Luckily, with jQuery fixing that kind of problem is easy.

With jQuery's height() function, you can read and set the height of any container (say, a div or a span. So if you have two such containers and you can't be sure which which one will be taller in the user's browser, you can just read their heights and increase the height of the shorter container to match that of the taller. Here's an example function to do just that:

function matchColHeights(col1, col2) {
	var col1Height = $(col1).height();
	var col2Height = $(col2).height();
	if (col1Height > col2Height) {
	} else {

Here's a demo with source code so you can give it a try:

<div id="firstCol" style="float: left; background-color: #060;">
Lorem ipsum...
<div id="secondCol" style="float: right; background-color: #006;">
Neque porro quisquam est, ...

<p style="clear: both; text-align: center;"><br />
<button onclick="matchColHeights('#firstCol', '#secondCol');">
   Match heights

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Quis autem vel eum iure reprehenderit , vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

Except, of course, you won't want to have the height adjustment happen only after a user clicks on a button for you. This tactic is the kind of thing you want to happen automatically, so just put it in the $(document).ready() function:

$(document).ready(function() {
	matchColHeights('#firstCol', '#secondCol');

Comments (1)

There's also a plugin for that. Very handy. http://plugins.jquery.com/project/equal-heights

Post a comment

Type the characters you see in the picture above.