Search code examples
htmlcssflexbox

How to make two columns with CSS?


I have an array of N elements:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>

I need to make two columns in following order:

If we have 10 elements:

1 6
2 7
3 8
4 9
5 10

If we have 9 elements:

1 6
2 7
3 8
4 9
5 

If we have 7 elements:

1 5
2 6
3 7
4 

And so on. CSS should devide elements into two columns.

The number of elements isn't a constant.

The code in react is pretty simple:

numList.map(item => (
            <div>{item}</div>
          ))

I can devide elements array into two arrays using js and then render it as two list separatelly and make columns for it with flex.

But I wish to know if there a way to do it with CSS only without JS.

How do I make two columns with CSS?


Solution

  • Based on your examples, I think just a simple columns: 2 would have this functionality.

    body {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
    
    .wrapper {
      columns: 2;
      border: 1px solid black;
    }
    <div class="wrapper">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      <div>7</div>
      <div>8</div>
      <div>9</div>
      <div>10</div>
    </div>
    
    <div class="wrapper">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      <div>7</div>
      <div>8</div>
      <div>9</div>
    </div>
    
    <div class="wrapper">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      <div>7</div>
    </div>