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) {
$(col2).height(col1Height);
} else {
$(col1).height(col2Height);
}
}
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>
<div id="secondCol" style="float: right; background-color: #006;">
Neque porro quisquam est, ...
</div>
<p style="clear: both; text-align: center;"><br />
<button onclick="matchColHeights('#firstCol', '#secondCol');">
Match heights
</button>
</p>
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)
March 31, 2010
10:35PM | #
There's also a plugin for that. Very handy. http://plugins.jquery.com/project/equal-heights