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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 14:34:10970browse

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

Displaying an Unordered List in Two Columns

Introduction

For modern browsers, the primary approach to displaying an unordered list in two columns involves utilizing the CSS3 columns module. However, for legacy browsers such as Internet Explorer, a JavaScript-based solution is necessary.

Modern Browsers

Using the CSS3 columns module, you can simply add the following CSS rules to achieve the desired effect:

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

Legacy Browsers

For legacy browsers, you can employ a JavaScript solution that involves DOM manipulation. Here's a JavaScript code example using jQuery:

$(function(){
    var initialContainer = $('.columns'),
        columnItems = $('.columns li'),
        columns = null,
        column = 1;

    function updateColumns(){
        column = 0;
        columnItems.each(function(idx, el){
            if (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');
    }

    setupColumns();
    updateColumns();
});

And here's the corresponding CSS:

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

Variant Display Option

The code provided above results in the following column arrangement:

A  E
B  F
C  G
D

To achieve the variant layout requested by the OP:

A  B
C  D
E  F
G

Modify the updateColumns() function as follows:

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 Can I 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