Home >Web Front-end >CSS Tutorial >How to Display an Unordered List in Two Columns Using CSS and JavaScript?

How to Display an Unordered List in Two Columns Using CSS and JavaScript?

DDD
DDDOriginal
2024-12-20 07:35:09516browse

How to Display an Unordered List in Two Columns Using CSS and JavaScript?

Displaying an Unordered List in Two Columns

Modern Browsers

To display an unordered list in two columns in modern browsers, utilize the CSS3 columns module:

CSS:

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

[JSFiddle Demo](http://jsfiddle.net/HP85j/8/)

Legacy Browsers

For Internet Explorer support, JavaScript and DOM manipulation are necessary:

HTML:

<div>
    <ul class="columns" data-columns="2">
        <li>A</li>
        <li>B</li>
        <li>C</li>
        <li>D</li>
        <li>E</li>
        <li>F</li>
        <li>G</li>
    </ul>
</div>

JavaScript (jQuery):

(function ($) {
    var initialContainer = $('.columns'),
        columnItems = $('.columns li'),
        columns = null,
        column = 1; // account for initial column
    function updateColumns() {
        column = 0;
        columnItems.each(function (idx, el) {
            if (idx !== 0 && idx > (columnItems.length / columns.length) + (column * idx)) {
                column += 1;
            }
            $(columns.get(column)).append(el);
        });
    }
    function setupColumns() {
        columnItems.detach();
        while (column++ < initialContainer.data('columns')) {
            initialContainer.clone().insertBefore(initialContainer);
            column++;
        }
        columns = $('.columns');
    }

    $(function () {
        setupColumns();
        updateColumns();
    });
})(jQuery);

CSS:

.columns {
    float: left;
    position: relative;
    margin-right: 20px;
}

Note: The initial JavaScript function orders the columns as follows:

A  E
B  F
C  G
D

To order the columns as requested by the OP:

A  B
C  D
E  F
G

Modify the updateColumns function to:

function updateColumns() {
    column = 0;
    columnItems.each(function (idx, el) {
        if (column > columns.length) {
            column = 0;
        }
        $(columns.get(column)).append(el);
        column += 1;
    });
}

The above is the detailed content of How to Display an Unordered List in Two Columns Using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn