skip to Main Content

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:
properly displayed grid

but breaks if the grid is bigger (for example with createGrid(100)):
broken grid

How do I make the grid display properly (as a square with a horizonal scrollbar)?

2

Answers


  1. You are using display: table but with display: grid and grid-auto-flow property, it should work. Try the below css.

    #container {
        padding-bottom: 25px;
        display: grid;   
        grid-auto-flow: row; 
    }
    
    #container > div {
        width: 100%;
        display: grid;   
        grid-auto-flow: column;  
    }
    
    #container > div > div {
        float: left;
        height: 25px;
        border: 1px solid #ccc;
        width: 25px;
    }
    
    Login or Signup to reply.
  2. 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.

    function createGrid(numberOfRows) {
      const container = document.getElementById('container');
      document.getElementById("container").innerHTML = "";
      container.setAttribute('style', `--cells: ${numberOfRows} `);
      console.log(numberOfRows);
      for (let i = 0; i < numberOfRows; i++) {
        for (let y = 0; y < numberOfRows; y++) {
          let divCell = document.createElement("div");
          container.appendChild(divCell);
        }
    
      }
    }
    window.onload = createGrid(100)
    #container {
      padding-bottom: 25px;
    }
    
    #container {
      width: 100%;
      display: grid;
      grid-template-rows: 25px;
      grid-template-columns: repeat(var(--cells), 25px);
    }
    
    #container>div {
      height: 25px;
      border: 1px solid #ccc;
      width: 25px;
    }
    <div id="container"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search