I encountered a situation where I needed to dynamically create a grid with square grids of dimensions MxN. Below is the code snippet for achieving this:
rerender = (event) => {
const height = document.getElementById("y-input").value;
const width = document.getElementById("x-input").value;
console.log(`${height} :: ${width}`);
const cellContainer = document.getElementById("cell-container");
cellContainer.style.gridTemplateRows = `repeat(${height}, 1fr)`;
cellContainer.style.gridTemplateColumns = `repeat(${width}, 1fr)`;
cellContainer.innerHTML = "";
[...Array(height * width).keys()]
.map(() => document.createElement('div'))
.map((e) => {
e.className = "cell";
return e
})
.map((e) => cellContainer.appendChild(e))
}
#grid-container {
width: 500px;
height: 500px;
background-color: aqua;
padding: 8px;
}
#cell-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(2, 1fr);
}
.cell {
background-color: blue;
min-width: 4px;
min-height: 4px;
margin: 1px;
aspect-ratio: 1/1;
}
<div>
<label for="x-input">width</label>
<input value=2 min=1 max=50 type="number" name="x" id="x-input" style="width: 4ch;" onchange="rerender(event)">
<label for="y-input">height</label>
<input value=2 min=1 max=50 type="number" name="y" id="y-input" style="width: 4ch;" onchange="rerender(event)">
</div>
<div id="grid-container">
<div id="cell-container">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</div>
I am utilizing a grid layout where the number of rows and columns can be adjusted dynamically using the following code:
cellContainer.style.gridTemplateRows = `repeat(${height}, 1fr)`;
cellContainer.style.gridTemplateColumns = `repeat(${width}, 1fr)`;
The cells are kept square by using the aspect-ratio
property. This approach works well for square grids and also when dealing with rectangular cases where the width is greater than the height.
In cases where the height is greater than the width (rectangular), there is an overflow issue. How can this overflow be prevented?