The CSS float property is often used to create columns. Waiting in the wings are some newer techniques such as the CSS column-count property which will make adding columns much easier.

For example given a HTML snippet of :

<ul>
<ul>
	<li>ALFA ROMEO</li>
	<li>AUDI</li>
	<li>AUSTIN</li>
	<li>BMW</li>
        .. etc etc
        <li>TOYOTA</li>
	<li>TRIUMPH</li>
	<li>VAUXHALL</li>
	<li>VOLKSWAGEN</li>
	<li>VOLVO</li>
</ul>

We can use the following CSS to put the list into 5 nice columns.

	column-count:5;
	column-gap:40px;
	column-rule-width:1px;
	column-rule-style:outset;
	column-rule-color:#ccc;

View Demo

This is particularly useful when your content (in this case a list) is dynamic and you don't know how many items you're doing to have and therefore how many items to place in each list.

A Javascript Fallback

However, as caniuse kindly tell us we can't use this technique with IE9 or earlier.

Here is a solution I came up with. Assuming we want 5 columns set up the HTML as follows:

<div id="colsContainer">
 	<div><ul></ul></div>
	<div><ul></ul></div>
	<div><ul></ul></div>
	<div><ul></ul></div>
	<div><ul></ul></div>
</div>

The dynamic data I am going to use here is a Javascript array.

var myArray = new Array('ALFA ROMEO','AUDI','AUSTIN','BMW', .... 'VOLKSWAGEN','VOLVO');

The following Javascript counts the number of values in the array and then works out how to distribute them evenly across, in this case, five columns. The maths trick here is the use of the modulus (%) to divide the items by the number of columns but distribute the remainder to the left-hand columns.

 var noCols = 5;
 var displayData = "";
 var startVal = 0;
 var endVal = 0;
 for(var i=0;i<noCols;i++){
     if(i < myData.length%noCols){
         endVal =+ (endVal+Math.floor(myData.length/noCols)+1);
     }else{
         endVal =+ (endVal+Math.floor(myData.length/noCols));
     }
     displayData = ""
     for(var j=startVal;j<endVal;j++){
         displayData += '<li><a href="">';
         displayData += myData[j];
         displayData += '</a></li>';
     }
     startVal = endVal;
     $('#modelList div ul').eq(i).html(displayData);
 }

View Demo

Leave a Comment