Auto extend DIV to match height of another

By Jonathan on

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}

{/code}

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!

About Jonathan

Jonathan likes playing with code, cars and ermm... digital things

Related Posts
Contact Form 7 & NextGEN Uploader Fix

Fixing NextGen to work with Contact Form 7, call to undefined function wpcf7_add_tag_generator()

Changing the default quantity on a Magento product page

A tutorial on how to update the Magento product page so that the customer doesn't have to enter a quantity to add...

WordPress Templates

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

JOIN THE CONVERSATION - LEAVE A COMMENT