Dividing Dynamic Content equally into Columns

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 :

	<li>ALFA ROMEO</li>
        .. etc etc

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


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">

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);
         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