Home > database >  Can grid items wrap?
Can grid items wrap?

Time:05-13

How can I make the grid-items wrap inside their container? cause whenever input 64 as a new grid size the grid-items would overflow out of its container. I want the grid-items to adjust to the size of the grid-container.

So basically, I want the grid-container to remain its size no matter how many newly grid-item is added.

const grid = document.querySelector('#grid-container');

function makeGrid(rows, cols) {
  for (let i = 0; i < (rows * cols); i  ) {
    grid.style.setProperty('--grid-rows', rows);
    grid.style.setProperty('--grid-cols', cols);
    let tile = document.createElement('div');
    grid.appendChild(tile).className = 'grid-item';
    //fill color
    tile.addEventListener('mouseover', () => {
      tile.style.backgroundColor = 'black';
    })
  }
}
makeGrid(16, 16);

function resizeGrid() {
  const resizeBtn = document.querySelector('#resize-btn');

  resizeBtn.addEventListener('click', () => {
    //remove default grid
    const gridItem = document.querySelectorAll('.grid-item');
    gridItem.forEach((item) => {
      grid.removeChild(item);
    })
    //create new grid
    let input = prompt('number of tiles per side');
    let rows = input;
    let cols = rows;
    makeGrid(rows, cols);
  })
}

resizeGrid();
:root {
  --grid-rows: 1;
  --grid-cols: 1;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

#resize-btn {
  padding: 5px 10px;
  margin-top: 5px;
  margin-bottom: 5px;
  background-color: #333;
  color: #f1f1f1;
  font-size: 16px;
  border: none;
  border-radius: 5px;
}

#grid-container {
  display: grid;
  grid-template-rows: repeat(var(--grid-rows), 1fr);
  grid-template-columns: repeat(var(--grid-cols), 1fr);
  min-width: 500px;
  min-height: 500px;
  border: 10px solid coral;
  background-color: rgb(247, 208, 194);
  border-radius: 10px;
}

.grid-item {
  border: 1px solid black;
  padding: 1em;
}
<div >
  <button id="resize-btn">Resize</button>
  <div id="grid-container"></div>
</div>

CodePudding user response:

Your layout adds columns and rows:

#grid-container {
   display: grid;
   grid-template-rows: repeat(var(--grid-rows), 1fr); 
   grid-template-columns: repeat(var(--grid-cols), 1fr);
}

Columns and rows don't wrap. They append to the existing set of columns or rows.

Hence, grid items in this layout won't wrap. They occupy the cells created by the new tracks.

If you want a layout where the items wrap, use the grid auto-fit or auto-fill functions, which limit the creation of columns or rows to the size of the container. Working together, these functions and limits enable grid items to flow across tracks.

Another option is flexbox, which doesn't generate column or row tracks, just flex lines.

These posts may provide further guidance:

  • enter image description here

  • Related