Parand Parand - 1 year ago 70
CSS Question

How to line up items of varied length in a resizable space in CSS?

I'd like to line up items approximately like this:

item1 item2 i3 longitemname
i4 longitemname2 anotheritem i5

Basically items of varying length arranged in a table like structure. The tricky part is the container for these can vary in size and I'd like to fit as many as I can in each row - in other words, I won't know beforehand how many items fit in a line, and if the page is resized the items should re-flow themselves to accommodate. E.g. initially 10 items could fit on each line, but on resize it could be reduced to 5.

I don't think I can use an html table since I don't know the number of columns (since I don't know how many will fit on a line). I can use css to float them, but since they're of varying size they won't line up.

So far the only thing I can think of is to use javascript to get the size of largest item, set the size of all items to that size, and float everything left.

Any better suggestions?

Answer Source

This can be done using floated div's, calculating the max width, and setting all widths to the max. Here's jquery code to do it:


<div class="item">something</div>
<div class="item">something else</div>


div.item { float: left; }


var max_width=0;
$('div.item').each( function() { if ($(this).width() > max_width) { max_width=$(this).width(); } } ).width(max_width);

Not too ugly but not too pretty either, I'm still open to better suggestions...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download