Change the height of all list items in order to float properly with jQuery

Posted on 07/20/11 1 Comment

Many times web developers use a floating unordered list in order to create a grid of items (like a product list). By using a list instead of a table, the developer doesn’t have to check if the number of items in the last row are less than the table columns and append the colspan attribute to the last td.

<table>
    <tr>
        <td>item 1</td>
        <td>item 2</td>
        <td>item 3</td>
    </tr>
    <tr>
        <td>last item</td>
        <td colspan="2"> </td>
    </tr>
</table>

Although the usage of a list will make the lives of the developer and web author easier and produce cleaner code there is a catch. If the height of all the list items is not the same the result is going to be something like this:

You can avoid that by setting the height of the list items and overflow:hidden in css but sometimes all the information is required to be visible.

I came up with a simple solution quite a while ago using just a few lines of jQuery.

Let’s say we have the following list

<ul class="floatinglist">
    <li>some information</li>
    <li>some more information</li>
    . . .
    <li>even more information</li>
</ul>

By adding the following js code to your page the problem is solved

$(document).ready(function(){
	var maxheight = 0;
	$('.floatinglist li').each(function(){
		if (maxheight < $(this).height()) {
			maxheight = $(this).height();
		}
	});
	$('.floatinglist li').height(maxheight);
});

Now all the list items get the height of the biggest one and they float as expected.

One Comment

  1. dlestarter says:
    Monday, October 22, 2012 at 11:27pm

    This is very simple, thank for this simple trick…we will use this for design our themes! 10x

Post a Comment

Your email is never published or shared. Required fields are marked *