Search code examples
cssflexboxmultiple-columnscss-gridcss-multicolumn-layout

How do I break html lists in columns, honoring alphabetical order in column direction?


what if I have a list like this:

<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
  <li>g</li>
  <li>h</li>
  <li>i</li>
</ul>

And want a rendering like this:

a | e | i
b | f |
c | g |
d | h |

I mean, broken into columns but honoring 'vertical' alphabetical order? Also, columns should be as 'tall' as the space available. So not fixed 4 rows like above. Nor fixed height container.

Is it possible? I know I can do it with flexbox but fixeng the container height. I took a look to grid specs too, but not sure if it's some way possible.

Any idea?


Solution

  • Try CSS grid like this:

    ul {
      margin: 0;
      padding: 0;
      list-style:none;
      height: 100vh;
      display: grid;
      grid-template-rows: repeat(auto-fit, 1.2em); /* define the heoght of one row here */
      grid-auto-flow: column;
      font-size: 50px;
    }
    
    body {
      margin: 0;
    }
    <ul>
      <li>a</li>
      <li>b</li>
      <li>c</li>
      <li>d</li>
      <li>e</li>
      <li>f</li>
      <li>g</li>
      <li>h</li>
      <li>i</li>
    </ul>