Auto extend DIV to match height of another

Auto extend DIV to match height of another

By Jonathan on February 28, 2012

I recently came across a web design issue where I basically wanted two columns, where one of which had a dynamic height. The height of this container would be worked out via a piece of jQuery. This piece of jQuery would check the height of one div (the div that contains our blog feed in this case) and then, if larger than the css height, expand the div height so they are equal length. There may be many reasons why you would want to do this, the one I have given was the situation I was in.

First off as I was working with WordPress I added the jQuery source into my wordpress header by placing the following code in the section of the header.php file.

{code type=html}{/code}

Next up we need to go to our footer.php file and copy in the jQuery that is going to do the work for us:

{code type=javascript}


Lets break that code down so that we can understand it. Firstly in the above code all that will need changing are the div locators. In my example ‘#sidebar’ is the div that I want to auto expand and ‘#main’ is the div that jQuery will get is height from. Remember if you need to change these locators # is for ID and . is for class.

We need to wrap out code within a function otherwise it will never get called, for this type of script we are best to put it within the document ready function. In this instance when the page is loaded/refreshed this script will be ran.

The Math function is basically saying “Calculate.whichismore(locate(#sidebar).grabheight,locate(#main).grabheight)” Hopefully that makes it easier to understand. Either the height of #sidebar or #main will be stored within the variable ‘highestCol’ depending on which is largest.

Next up the jQuery will locate the div #sidebar and change the height property to whatever value is stored within the variable ‘highestCol’.

This should work like a dream, Happy coding!

Falkon blog post featured image for post - WordPress Templates

WordPress Templates

Ever wanted to customise a single page in WordPress with the template system but never knew how? Its simple with...