Javascript Same Height Div’s

Recently I had to make some divs the same height. Usually I would just pad the bottom of a div with page breaks but I couldn’t do that this time round as the page content is dynamic and the height of the divs could change.

First thing I did was look online for answers and sure enough there were solutions but looking at them they seemed over complicated so I decided to write my own solution.

Javascript Code:

function sameHeight(divs) // Bring in an array of your divs
{
var highest = 0;
for(i = 0; i < divs.length; i++) // Loop through the divs
{
document.getElementById(divs[i]).style.height = "auto";
// Check to see if this div is the highest?
if(document.getElementById(divs[i]).offsetHeight > highest)
{
// Yes its the highest so set the highest value to this div's height
highest = document.getElementById(divs[i]).offsetHeight;
}
}
// Loop through all divs again
for(i = 0; i < divs.length; i++)
{
// Set all divs height to the highest value
document.getElementById(divs[i]).style.height = highest+"px";
}
}

Then to run this code:

window.onload=function()
{
	sameHeight(new Array('block_01','block_02','block_03'));
}

Simply pass an array of your divs to the function. Easy peasy….

Just an extra word of warning… Be aware of using padding on the blocks you pass to this function. If the paddings are different in each block then they may not end up being the same height. Although you could modify the function to check for the use of padding and alter the heights accordingly.

No comments yet. Be the first.
Leave a reply

You must be logged in to post a comment.