How to Equalize the Heights of DIVS Using jQuery

jquery logo.png

In many web designs the designer may have requested for some page elements to be the same size. There are various ways to accomplish this. In this lesson we will consider using jQuery to equalize div heights.

Let's consider the following page layout where we have a left sidebar, main content, and a right sidebar.

As you can see we have 3 different heights.

divHeights.png

There are various ways to set all of the heights to be equal but for this lesson we will work with jQuery.

First, let's consider what needs to happen:

  1. We need to set a variable to track the maximum height

  2. We need to check each div in turn against the maximum height. If the height of the div is greater than the current maximum then we need to update that figure.

  3. Once we have been through each of the div elements then we need to set the height of each to the maximum height.

Let's have a look at the code to achieve this:

Line 1: we start with our document ready function. This code will not run until the page has fully loaded and the document is ready.

Line 3: this is the variable that will track the maximum height of all checked div elements

Line 5: we loop through all of the div elements using the each function. For each of the found divs we run a function.

Line 6: we check if the height of the current div is greater than the height currently stored in the maximumHeight variable. If it is greater then we process the next line.

Line 7: change the maximumHeight to the height of the current div.

Line 11: we change all div heights to the value of maximumHeight

The result is shown below:

divHeightAfter.png

Did you find this lesson useful? Please consider making a donation to help maintain these free tips.

Donate $1