Posts Tagged ‘css’

The easiest way to split your unordered list into columns is by assigning css classes.

<ul>
<li class="left">Item 1</li>
<li class="left">Item 2</li>
<li class="right_first">Item 3</li>
<li class="right">Item 4</li>
</ul>
.left {
margin-left: 0px;
}

.right {
margin-left: 50%;
}

.right_first {
margin-top: -40px;
}

If you know the size of the list then you can play around with the top margin of the “right_first” class. In our case, we do not know the size of the list, so we would have to do some black magic…

// First we calculate some variables
// the minimum column length (items / 2) at which to split into columns
var columnSplitLength = 7;
// the current would be column length
var currentColumnLength = Math.round(items.length / 2);
// is the items an odd or even length
var isOdd = (items.length > 2) != currentColumnLength;
// should we split the columns?
var shouldSplitColumns = currentColumnLength > columnSplitLength; 

var count = 1; var myLiHeight = 13; // height of each ListItem

$.each(items, function() {
    var className = shouldSplitColumns &&  (count > currentColumnLength) ? "right":"left";
    if(count == currentColumnLength+1)
        className = "right_first";
    var resultRow = $.stringFormat("<li class='{0}'>{1}</li>", [className, this.name]);
    $(resultRow).appendTo("#myUlList");
    count++;
});

// If the list length is odd, we have to add a phantom item to the right to balance
if(isOdd) {
 $("<li class='right'></li>").appendTo("#myUlList");
count++;
}
// Lastly, reset the first item of the right column to the top
$(".right_first").css("margin-left", "50%");
$(".right_first").css("margin-top", "-"+count*myLiHeight+"px");