Home > Software design >  Split items into two columns CSS grid
Split items into two columns CSS grid

Time:05-05

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.

CodePudding user response:

What about using grid? Only thing you will get another flow you expected.

.container {
  display: grid;
  grid-template-columns: repeat(2, minmax(50px, 1fr));
  grid-gap: 1rem;
  width: fit-content;
}

.container>div {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  background-color: tomato;
  aspect-ratio: 1/1;
}

hr {
  margin-top: 2rem;
  margin-bottom: 2rem;
}
<div >
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

<hr />

<div >
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

CodePudding user response:

Credits for the grid go to @YaroslavTrach but the order of HTML elements can be achieved by splitting your elements into two arrays and then alternating between them when rendering.

const elements = [ 1, 2, 3, 4, 5 ];
const half = Math.ceil(elements.length / 2);

const firstHalf = elements.slice(0, half);
const secondHalf = elements.slice(-half   1);

const toDiv = (i) => i ? `<div>${i}</div>` : ``;

document.getElementById('container').innerHTML = `
  ${firstHalf.map((el, id) => toDiv(el)   toDiv(secondHalf[id])).join('')}
`;
#container {
  display: grid;
  grid-template-columns: repeat(2, minmax(50px, 1fr));
  grid-gap: 1rem;
  width: fit-content;
}

#container>div {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  background-color: tomato;
  aspect-ratio: 1/1;
}
<div id="container">
</div>

  • Related