htmlcssflexboxcss-multicolumn-layout

Flexbox columns in ascending order


I'm working with some items in a list:

<ul>
  <li>Item1</li>
  <li>Item2</li>
  <li>Item3</li>
  <li>Item4</li>
  <li>Item5</li>
  <li>Item6</li>
  <li>Item7</li>
  <li>Item8</li>
</ul>

and I'm trying to get them to break into two columns using flexbox, which gives the result of this:

+--------------------+
|                    |
| Item1       Item2  |
|                    |
| Item3       Item4  |
|                    |
| Item5       Item6  |
|                    |
| Item7       Item8  |
|                    |
+--------------------+

But I'm trying to sort them in ascending order so it appears like this:

+--------------------+
|                    |
| Item1       Item5  |
|                    |
| Item2       Item6  |
|                    |
| Item3       Item7  |
|                    |
| Item4       Item8  |
|                    |
+--------------------+

Not sure how to achieve that by using CSS + Flexbox unless I need to add some JS into the mix?

Here's a demo on Codepen:

https://codepen.io/ultraloveninja/pen/drKLzG


Solution

  • Use a column flexbox and set a height for the ul - see demo below:

    ul {
      list-style: none;
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;
      width: 100%;
      max-width: 150px;
      height: 8em;
    }
    
    li {
      margin: 5px;
    }
    <ul>
      <li>Item1</li>
      <li>Item2</li>
      <li>Item3</li>
      <li>Item4</li>
      <li>Item5</li>
      <li>Item6</li>
      <li>Item7</li>
      <li>Item8</li>
    </ul>

    Or you can use CSS columns - see demo below:

    ul {
      list-style: none;
      columns: 2; /* added this */
      width: 100%;
      max-width: 150px;
      height: 8em;
    }
    
    li {
      margin: 5px;
    }
    <ul>
      <li>Item1</li>
      <li>Item2</li>
      <li>Item3</li>
      <li>Item4</li>
      <li>Item5</li>
      <li>Item6</li>
      <li>Item7</li>
      <li>Item8</li>
    </ul>