Setting Equal Heights with jQuery

JavaScript to the rescue

Calling equalHeights() on DOM ready let’s us keep all of the important factors in play, without adding extra markup or complex CSS workarounds:

cdl_capture_2011-09-06-40_ 000

  • usability. This is strictly a visual effect, so when the script is absent, columns are of varying heights and the page remains totally usable.
  • layout flexibility. The script assigns a min-height value (not height), so when content is added through user interaction or via AJAX running in the background, or if the user increases the browser text size, the content box will grow to fit. Columns or boxes can keep their percentage or em-based widths.
  • performance. It’s lightweight — has a small footprint, and doesn’t insert any DOM elements or require extra markup — and unobtrusive because, like other jQuery plugins, it’s called on standard CSS selectors.

How it works

equalHeights() loops through the top-level child nodes of a specified element and sets their min-height values to that of the tallest. It’s set up as a standard jQuery plugin, and is called on the container element:

$('.container').equalHeights();

In our version of the script the default unit is set to ems so that the content boxes will scale. This requires another of our methods, pxToEm; if it’s not present, the default unit reverts to pixels. Or, if you’re using pxToEm, you can override the default and pass a "true" argument to set the unit in pixels.

View in a new window

Leave a comment