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 class="container">
<button id="resize-btn">Resize</button>
<div id="grid-container"></div>
</div>