Here is what I have tried so far:
$('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>
This is same as the code that I have referred from another stack overflow question. Here is the link.
But I have tried to restrict the number of rows and have done my research, but I wasn't able to find any solution.
Looking for primarily CSS solution, but JavaScript is also accepted.
This is the simplest way to do it. CSS only. add width to the ul element. add display:inline-block and width of the new column (should be less than half of the ul width).
column-count can be auto or an integer. Use auto if you are also using column-width . Think of it as a way of telling the browser, to let column-width take the lead. The integer, also known as the number of columns, must be greater than or equal to 0.
CSS Multi-column Layout is a module of CSS that adds support for multi-column layouts.
It looks like the following is what you want:
var numitems = $("li").length; //get the amount of li elements, but you can be a little more specific depending on what your html structure is like
$("ul").css("column-count",numitems/2); //then just divide that by two and give that as the column count to your ul
li {
width: 100px;
height: 100px;
margin-top: 10px;
margin-right: 10px;
display: inline-block;
}
<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>
Note: I wouldn't necessarily go this route. I would take a look at css-grid or flexbox
More Info: The reason I wouldn't go this route is because ul
doesn't have the greatest support to do this, while something like css grid can do stuff like this out of the box. There's a little bit of a learning curve, and I can see some scenarios where this would be preferable to it, but I decided to mention it because it's worth considering.
There is a problem in your JS code. You can do it jQuery way. Try $(this).children()
instead of this.childNodes
.
$('ul').filter(function() {
return $(this).children().length > 5;
}).addClass('twoColumns');
ul.twoColumns {
list-style: none;
columns: 2;
-webkit-columns: 2;
-moz-columns: 2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.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>
<br><br>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With