ALAN
ALAN

Reputation: 495

How to add li element in ul as 2 columns

I have to add li element dynamically as columns, like this picture

i have one li element , and i want to append li element like this picture, one coluumn has to be have 4 li,, if element is 5. it has to add to another row, possible?

enter image description here

Upvotes: 0

Views: 756

Answers (5)

otinanai
otinanai

Reputation: 4025

You can use only one ul with nth-child(odd), nth-child(even) selectors to target half of the elements and float them left and right accordingly.

Take a look at this demo: http://jsfiddle.net/x9kxd/

Of course you miss the order of your <li> elements but at least you get a nice and simple solution for a two-column container.

---EDIT---

If your <li> elements need to change column after 4 items then you should use the nth-child(-n+4) selector. This way you keep the order as you want it.

Here's the demo: http://jsfiddle.net/QqudC/1/

The :nth-child() selector is supported in all major browsers, except IE8 and earlier.

Upvotes: 0

user1705630
user1705630

Reputation:

You could use CSS columns. It seems to be exactly what you are looking for: http://jsfiddle.net/ewsMh/.

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

I think there are polyfills for unsupported browsers.

Upvotes: 2

andyzinsser
andyzinsser

Reputation: 2543

Here is your DOM:

<ul id="left"></ul>
<ul id="right"></ul>

The function that adds li's (using jquery):

var addLi = function($li) {
    var $uls = $('ul');
    $.each($uls, function(index, ul) {
        // If this ul has less than 5 li's
        // then add the li here
        if ($(this).find('li').length < 5) {
            $(this).append($li);
            // exit the for loop since we have placed this li
            return;  
        }
    }
};
addLi('<li>Test</li>');

Upvotes: 1

Ravi Gadag
Ravi Gadag

Reputation: 15861

you can do like this.

var liLength;
$("#btnAddLi").click(function() {
liLength=$('#yourLastUl li').length;
if(liLength>4)
    $("#CreateOneMoreUL").append("<li>Content</li>");
else
    $("#yourLastUL").append("<li>Content</li>");
});

Upvotes: 0

Mr_Green
Mr_Green

Reputation: 41832

In my opinion, take two ul with same class name and with different ID's. make them arranged adjacent to each other. while adding the li dynamically, count the additions with a counter variable. If the addition is more than 4 then just add to another ul tag(change the ID with which you are functioning).

Upvotes: 0

Related Questions