0

I would like to build a dynamically filled grid. The grid has 2 columns but if the number of blocks is odd, I would like the last row to fill both columns. As the blocks are dynamically added, I can't put a class on the last element and I don't know how many blocks there will be.

Expected: Expected

I use grid layout but i miss something :

.container {    
display: grid;
grid-template-columns: repeat(2, 1fr);
justify-content: flex-start;
align-items: center;
}
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • 2
    Does this answer your question? [How to make the items in the last row consume remaining space in CSS Grid?](https://stackoverflow.com/questions/54370822/how-to-make-the-items-in-the-last-row-consume-remaining-space-in-css-grid) – Rayees AC Sep 01 '20 at 07:00

1 Answers1

1

You should go for flexbox as suggested by @RayeesAC in his comment. But If you still want to use Grid, you can do something like this with javascript-

growOrShrink();


function growOrShrink() {
  const container = document.querySelector('.container');
  const items = container.children
  const itemsNum = items.length;


  // if it's odd number of items
  if(itemsNum % 2) {
    items[itemsNum - 1]
      .classList.add('grow');
  }

  else {
    items[itemsNum - 1]
      .classList.remove('grow');

    items[itemsNum - 2]
      .classList.remove('grow');
  }
}
.container {  
  width: 100vw;
  height: 100px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  justify-content: flex-start;
  align-items: center;
}

.item {
  background: gray;
  border: 1px solid black;
}

.item.grow {
  grid-column: 1/3;
}
<div class='container'>
  <div class='item'>item1</div>
  <div class='item'>item2</div>
  <div class='item'>item3</div>
</div>
Sapinder Singh
  • 559
  • 6
  • 21