Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting list of items in two columns with CSS

I have a list of items (fetched from CMS) whose number is unknown. I need to display this list in two columns of roughly equal number of items. The following code works but I explain below why it's problematical:

<ul>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
</ul>

ul {
  display: flex;
  flex-wrap: wrap;
}

It's all good if the items' content is always the same height. But when one item has a much longer content in it, the sibling item on the same row is forced to expand to match the same height. I don't want that. I want the two columns to be completely independent in terms of items' height.

Possible with CSS alone?

EDIT:

Here is a JSfiddle exposing the problem: https://jsfiddle.net/g9p3m2dp/

like image 323
drake035 Avatar asked May 01 '17 21:05

drake035


1 Answers

ul {
  -webkit-columns: 2;
     -moz-columns: 2;
          columns: 2;
  padding-left: 0;
}
ul li {
  list-style-position: inside;
  -webkit-column-break-inside: avoid;
            page-break-inside: avoid;
                 break-inside: avoid;
}
<ul>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
</ul>

Note columns is actually a shorthand for <'column-width'> || <'column-count'>. This means you can also specify the width (in px, %, em, cm, in...) instead of specifying the number of columns.

Also note you need to set list-style-position: inside; for ol and ul elements to display their children <li>s bullets (or numbers) on the right side column, except for Firefox, which sets list-style-position to inside by default.

like image 76
tao Avatar answered Oct 01 '22 00:10

tao