I am generating a grid dynamically like so:
function createGrid(numberOfRows) {
document.getElementById("container").innerHTML = "";
console.log(numberOfRows);
for (let i = 0; i < numberOfRows; i++) {
var divRow = document.createElement("div");
document.getElementById("container").appendChild(divRow);
for (let y = 0; y < numberOfRows; y++) {
let divCol = document.createElement("div");
divRow.appendChild(divCol);
}
}
}
window.onload = createGrid(10)
#container {
padding-bottom: 25px;
}
#container>div {
width: 100%;
height: 10px;
}
#container>div>div {
float: left;
height: 25px;
border: 1px solid #ccc;
width: 25px;
}
div {
display: table;
margin: auto;
}
<div id="container"></div>
This works perfectly if the grid fully fits on the screen:
but breaks if the grid is bigger (for example with createGrid(100)):
How do I make the grid display properly (as a square with a horizonal scrollbar)?
2
Answers
You are using
display: table
but withdisplay: grid
andgrid-auto-flow
property, it should work. Try the below css.Don’t use floats, use
display: grid
for displaying a grid.In my solution I set the cells of the grid as inline style and use this then in CSS to define how many cells there should be in a row.