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
How to Blog

Many of our clients ask us about how to write a good blog, especially for SEO, so we decided to put our...

Protecting your WordPress website

Ever been hacked or just want to be protected in case a hacker comes knocking at your backdoor? A few simple steps...

Magento Error: change default phone numbers before site launch

A simple fix to the "Reminder: Change Magento`s default phone numbers and callouts before site launch" bug in magento.

JOIN THE CONVERSATION - LEAVE A COMMENT