Search code examples
csscss-grid

Split items into two columns CSS grid


Is there a way to achieve the following via CSS grid?

  1. If the number of items is odd, the first column should have 1 more row than the second column.
1 4
2 5
3
  1. If the number of items is even, the columns should have the same number of rows.
1 3 
2 4

Tried using grid-template-rows but the number of rows per column is fixed.


Solution

  • Even though the question explicitly states "via CSS grid", I think it's worth adding an easy way to do this without grid. Especially since all grid-based approaches seem to require you to hard-code the number of desired rows.

    To divide any number of items in to two columns, you can use the column-count css property like so: column-count: 2.

    This property meets the requirements for:

    • going top-to-bottom before left-to-right,
    • balancing the columns, prioritizing the first column when there is an odd number of elements

    #twocol {
      column-count: 2;
    }
    <div id="twocol">
      <div>Item 1</div>
      <div>Item 2</div>
      <div>Item 3</div>
      <div>Item 4</div>
      <div>Item 5</div>
      <div>Item 6</div>
    </div>
    
    <button onclick="twocol.innerHTML += `<div>Item ${twocol.children.length + 1}</div>`">Add item</button>