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
Managing your website using WordPress

A very lenghty post that covers the basics of managing your content and news posts for your website, if you're using WordPress...

Make your own jQuery Slider

I've begun using this little feature more and more in recent projects, not only because I like it but Luke includes it...

Tutorial: Illustrating Stallone in the Expendables

A mini tutorial showing how to create a Sylvester Stallone illustration from a movie poster, using an iPad, Illustrator, Photoshop and a...

JOIN THE CONVERSATION - LEAVE A COMMENT