Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
How to make simple grid in javascript

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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
}
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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;
        }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!