Home > Software design >  How to make simple grid in javascript
How to make simple grid in javascript

Time:01-19

I want to make a simple grid with for loop so that the code below will create a 5 (row) * 4 (column) grids.

 for(let i=0;i<20;i  ){
 let div = document.createElement('div')
 document.body.appendChild(div)
 div.textContent = i
 }
div{
width:200px;
height:200px;
text-align:center;
border:2px solid red
display:grid;
 grid-column-gap: 50px;
 grid-row-gap: 50px;
}

I have check some documentation before asking this question, but I still don't know how to create grid using for loop so that the item will follow the format I want.

I want the grid to display every 4 in a row and the left to display in the next row.

Output should look like:

1 2 3 4
5 6 7 8 
9 10 11 12
13 14 15 16 
17 18 19 20

Anyone, please help me! Sorry I am bad at Javascript.

CodePudding user response:

It is the body (the parent of the divs) which you want to be displayed as a grid.

So set the grid styling on body not the individual items.

Also you can tell it how may items you want in a row (ie how many columns) using grid-template-columns. In this case as you have fixed the width of each item you just want it to use the items' widths. If you wanted it to fill the available space, the width of the parent, then you'd use 1fr instead of auto.

for (let i = 0; i < 20; i  ) {
  let div = document.createElement('div')
  document.body.appendChild(div)
  div.textContent = i
}
body {
  display: grid;
  grid-column-gap: 50px;
  grid-row-gap: 50px;
  grid-template-columns: repeat(3, auto);
}

div {
  width: 200px;
  height: 200px;
  text-align: center;
  border: 2px solid red;
}
<body>
</body>

CodePudding user response:

Credit to @A Haworth

body { display:grid;
 grid-column-gap: 50px;
 grid-row-gap: 50px;
}
div{
width:200px;
height:200px;
text-align:center;
border:2px solid red
}

CodePudding user response:

for (let i = 1; i <= 5 * 4; i  ) {
            let div = document.createElement('div')
            document.body.appendChild(div)
            div.textContent = i
        }
        
div {
            width: 25%;
            height: 50px;
            text-align: center;
            float: left;
        }

  •  Tags:  
  • Related