Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 430
TorK Avatar asked Oct 19 '15 14:10

TorK


People also ask

How we can span one or more pieces of content across multiple columns?

The column-span CSS property makes it possible for an element to span across all columns when its value is set to all .

How do you display data in two columns in HTML?

The following syntax is used to add columns in HTML. <div class="row"> tag is used to initialize the row where all the columns will be added. <div class="column" > tag is used to add the corresponding number of columns. style="background-color:#aaa;" property is used to give color to the column.

How do I make a list in two columns?

Inside of the "Page layout" tab, click on "Columns" to see your column options for the document. Select the "Two" option, represented by both the word and an icon displaying two parallel columns of text. This divides your current word document into two even columns.


2 Answers

If you are able to use CSS grid you can do this with grid-template-rows and grid-auto-flow directive. Grid can be used in most browsers natively and in IE11 with autoprefixer:

.list {
  display: grid;
  grid-template-rows: repeat(5, min-content);
  grid-auto-flow: column;
}
<ul class="list">
  <li class="item">1</li>
  <li class="item">2</li>
  <li class="item">3</li>
  <li class="item">4</li>
  <li class="item">5</li>
  <li class="item">6</li>
  <li class="item">7</li>
</ul>
like image 179
Hunter McMillen Avatar answered Oct 04 '22 13:10

Hunter McMillen


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>
like image 38
A. Wolff Avatar answered Oct 04 '22 13:10

A. Wolff