EN
JavaScript - dynamically create grid of divs using flexbox
3 points
In this article, we would like to show you how to dynamically create a grid of HTML div elements using JavaScript.

In order to create the grid, we need to take the following steps:
- create grid container to store cells/rows/columns,
- set the grid element's
display
property value toflex
, - set the column element's
flex
property value to1
, - using
appendChild()
method append cells/rows/columns.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.grid {
7
display: flex; /* <--- required */
8
}
9
10
.column {
11
flex: 1; /* <--------- required (makes each column with the same width) */
12
}
13
14
.cell {
15
margin: 2px;
16
background: gold;
17
text-align: center;
18
}
19
20
</style>
21
</head>
22
<body>
23
<script>
24
25
var columns = 3;
26
var rows = 4;
27
28
var grid = document.createElement('div'); // creates grid
29
grid.className = 'grid';
30
for (var i = 0; i < columns; ++i) {
31
var column = document.createElement('div'); // creates column
32
column.className = 'column';
33
for (var j = 0; j < rows; ++j) {
34
var cell = document.createElement('div'); // creates cell
35
cell.className = 'cell';
36
cell.textContent = (i + 1) + '-' + (j + 1); // sets text in cell
37
column.appendChild(cell); // appends cell to column (as row)
38
}
39
grid.appendChild(column); // appends column to grid
40
}
41
document.body.appendChild(grid); // appends grid to webpage
42
43
</script>
44
</body>
45
</html>