Have you ever seen a site where there are boxes in a row or column that all have differnet heights or widths? I know I have, and it really looks like the developer didn't take the time to align them corectly. In this article we are going to build two functions that we can use on any set of HTML elements on your page and set their width or height to the largest element.

Set HTML Elements To Use With Our Functions.

First we need some elements to use with our javascript code. Below I am using a few div tags with some styles in them. Notice I have given them all the same class name.

//HTML Code
<div class="element" style="float:left;border:1px solid black;height:100px;width:100px;"><h2>Item 1</h2><p>Blah</p></div>
<div class="element" style="float:left;border:1px solid black;height:200px;width:50px;"><h2>Item 2</h2><p>Blah</p><p>Blah</p></div>
<div class="element" style="float:left;border:1px solid black;height:300px;width:200px;"><h2>Item 3</h2><p>Blah</p><p>Blah</p><p>Blah</p></div>
<div class="element" style="float:left;border:1px solid black;height:400px;width:150px;"><h2>Item 4</h2><p>Blah</p><p>Blah</p><p>Blah</p><p>Blah</p></div> <

Function To Set Elements The Same Height.

This is our first function that will set all elements in the set the same height. We will be using jQuery to help us select the elements.

//JavaScript Code function
function getMaxHeight(elements) {
    var maxHeight = 0;
    $(elements).each(function () {
        if ($(this).height() > maxHeight) {
            maxHeight = $(this).height();

No that we have our HTML and jQuery script ready we have to call the script with the following code. Just a side note to make sure you put all your scripts at the bottom of your page right before the closing tag.

$(document).ready(function () {

Function To Set Elements The Same Width.

The second function will be used to set the same set of elements to the same width. The largest width will be used to set them all.

function getMaxWidth(elements) {
    var maxWidth = 0;
    $(elements).each(function () {
        if ($(this).width() > maxWidth) {
        maxWidth = $(this).width();

And here is the code to set the div's

$(document).ready(function () {

Hope this helps!


Most Visited