Search code examples
javascripthtmlcsscss-grid

css grid cells don't fill all available space when the gird is 64 x 64


I am trying to make an etch a sketch project, and fill a nxn grid with equal width and height cells. Now, if i make the grid of 8x8 cells, 16x16 or 32x32 i get no problems, but when the grid is 64x64, the cells don't fit in the last column of the grid, even if there is available space.

if someone could help it'd be amazing :)

this is the weird behavior i get:

css grid weird behaviour

the html and css is this:

let grid = document.querySelector("#grid");

let size = 64;

let width = grid.clientWidth;
console.log(width);

grid.setAttribute("style", `grid-template-columns:repeat(auto-fill,${width/size}px); grid-template-rows:repeat(auto-fill,${width/size}px);`);

for (let i = 0; i < size * size; i++) {
  const div = document.createElement("div");
  div.classList.add("cell");
  div.addEventListener("mouseover", (e) => {
    e.target.setAttribute("style", "background-color:black;");
  });
  grid.appendChild(div);
}
* {
  margin: 0;
  padding: 0;
}

#grid {
  display: grid;
  width: 600px;
  height: 600px;
  grid-template-columns: repeat(auto-fill, 75px); /* width / n of columns */
  grid-template-rows: repeat(auto-fill, 75px); /* height / n of rows */
  background-color: white;
  border: solid black 10px;
}

.cell {
  border: solid black 1px;
}
<div id="grid">
</div>


Solution

  • You don't need to do a lot of calculation, you can simplify like below and avoid the use of float number where you will have rounding issues (especially on Firefox)

    let grid = document.querySelector("#grid");
    
    let size = 64;
    
    grid.style.setProperty("--n", size);
    
    for (let i = 0; i < size * size; i++) {
      const div = document.createElement("div");
      div.classList.add("cell");
      div.addEventListener("mouseover", (e) => {
        e.target.setAttribute("style", "background-color:black;");
      });
      grid.appendChild(div);
    }
    * {
      margin: 0;
      padding: 0;
    }
    
    #grid {
      display: grid;
      width: 600px;
      height: 600px;
      grid-template-columns: repeat(var(--n,32), 1fr); /* number of column here*/
      background-color: white;
      border: solid black 10px;
    }
    
    .cell {
      border: solid black 1px;
    }
    <div id="grid">
    </div>