Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to show list items as 2 or more columns (dynamic alignment)

I am able to do the list using float:left; like this

enter image description here

But I would like to show it like this (as 2 or more columns)

enter image description here

How can I do that?

@sandeep gave good solution. Unfortunately does not work in IE(need ie7 and above).

any help?

like image 209
The Unshaped Man Avatar asked Nov 11 '11 10:11

The Unshaped Man


3 Answers

For this, you can use the column-count property:

div#multicolumn1 {
    -moz-column-count: 2;
    -moz-column-gap: 50%;
    -webkit-column-count: 2;
    -webkit-column-gap: 50%;
    column-count: 3;
    column-gap: 50%;
}

Check this jsFiddle.

Note: It does not work in IE.

For IE, you can use this JavaScript: CSS3 - Multi Column Layout Demonstration

like image 156
sandeep Avatar answered Nov 18 '22 09:11

sandeep


This works just fine cross-browser, no JS required. You just limit the width of your columns.

<style>
    ul.col {width:60px;float:left;margin:0 5px 0 0;padding:0;}
    ul.col li {width:50px;background:#999;list-style-type:none;margin:0 0 5px 0;padding:5px;}
</style>

<ul class="col">
    <li>1(li)</li>
    <li>2(li)</li>
    <li>3(li)</li>
    <li>4(li)</li>
    <li>5(li)</li>
</ul>
<ul class="col">
    <li>6(li)</li>
    <li>7(li)</li>
    <li>8(li)</li>
    <li>9(li)</li>
    <li>10(li)</li>
</ul>

If you are stuck with them all in one UL on page load, you can split them out with jQuery to create the same results:

<script>
$(function(){ //on document ready
    var perCol = 5;
    var $ul = $('ul.col');
    var rows = Math.ceil($ul.find('li').length/perCol);
    for(var i=1;i<=rows;i++){
        $ul.after('<ul class="col"></ul>');
    }
    for(var i=1;i<=rows;i++){
        $ul.find('li:lt('+(perCol)+')').appendTo('ul.col:eq('+(i)+')');
    }
    $ul.remove();
});
</script>
like image 4
Will Stern Avatar answered Nov 18 '22 08:11

Will Stern


As long as your list items are a fixed width, like in your examples, couldn't you just do something like in this fiddle? http://jsfiddle.net/swNYE/1/

And wherever your list gets spit out, simply apply the "left" class to the first half, and the "right" class to the second half. If you're dynamically adding content through Javascript, then you'd simply run through the li's each time something is added, and apply the new correct class.

HTML:

<ul>
    <li class="left">1</li>
    <li class="left">2</li>
    <li class="left">3</li>
    <li class="left">4</li>
    <li class="right">5</li>
    <li class="right">6</li>
    <li class="right">7</li>
    <li class="right">8</li>
</ul>

CSS:

li {
    width: 100px;
}
li.left {
    float: left;
    clear: left;
}
li.right {
    margin-left: 100px;
}
like image 4
justisb Avatar answered Nov 18 '22 09:11

justisb