Explain Codes LogoExplain Codes Logo

How to display an unordered list in two columns?

html
responsive-design
css-grid
javascript
Anton ShumikhinbyAnton Shumikhin·Jan 18, 2025
TLDR

To effortlessly create a two-column layout for an unordered list, apply the column-count CSS property:

ul { column-count: 2; }

Your HTML should be:

<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul>

This partition your list into two columns, guaranteeing a balance distribution of list items.

Taking advantage of modern CSS

Apart from column-count, modern CSS gives us a feast of extensive options to prepare multi-column layouts while preserving the semantic structure.

Grid layout to the rescue

Grid layout converges to an elegant solution:

ul { display: grid; grid-template-columns: repeat(2, 1fr); /* Grid - because we love playing with our food */ justify-content: start; /* Line them up! */ grid-auto-flow: column; /* flow like a river, column wise */ }

This solution produces a two-column grid for your list items and fares quite well for responsive designs.

Responsive designs and legacy browsers

While wielding modern options, pay critical attention to responsive designs and tailoring to legacy browsers. float: left combined with a calculated width could serve effectively:

ul li { float: left; /* Some things just can't be floated away */ width: 50%; /* Sharing is caring, 50-50! */ list-style-position: inside; /* Bullets inside, like a surprising birthday present */ }

List column magic with JavaScript

For previous-generation browsers that might not support CSS Grid or column-count, bring in JavaScript to manipulate the DOM effectively:

var $list = $('ul'); var listItems = $list.children('li'); var listLength = listItems.length; var middle = Math.ceil(listLength / 2); /* Because Math is helpful outside school too */ /* Let JavaScript pull a rabbit out of our <ul> */ $list.after($list.clone().addClass('column-two')); $('.column-two').html(''); listItems.each(function(i){ $(this).appendTo(i < middle ? $list : $('.column-two')); /* Here we go round the mulberry bush */ });

This logic effectively splits the list in half and distributes the items evenly in two separate columns.