TorK TorK - 1 month ago 5
CSS Question

CSS/html display list in two columns if more than X amount of elements?

I have a dynamic list of elements.
I do not want this list to be too long.
I could use:

ul {
columns: 2;
-webkit-columns: 2;
-moz-columns: 2;
}


But this always results in two columns. I would prefer to only have one column if there are only a few elements in the list.
So with 5 elements or less, I want this:

1
2
3
4
5

But with 6 or more elements I want this:

1 4
2 5
3 6

I use css3, html, bootstrap 2.3.2 and jquery
Do anyone have some tips for the best way to do this?

Answer

You could simply filter ul element(s):

$('ul').filter(function(){
    return this.childNodes.length > 5
}).addClass('twoColumns');
ul.twoColumns {
  list-style: none;
    columns: 2;
    -webkit-columns: 2;
    -moz-columns: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>

Comments