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.
Practical example
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
displayproperty value toflex, - set the column element's
flexproperty value to1, - using
appendChild()method append cells/rows/columns.
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<head>
<style>
.grid {
display: flex; /* <--- required */
}
.column {
flex: 1; /* <--------- required (makes each column with the same width) */
}
.cell {
margin: 2px;
background: gold;
text-align: center;
}
</style>
</head>
<body>
<script>
var columns = 3;
var rows = 4;
var grid = document.createElement('div'); // creates grid
grid.className = 'grid';
for (var i = 0; i < columns; ++i) {
var column = document.createElement('div'); // creates column
column.className = 'column';
for (var j = 0; j < rows; ++j) {
var cell = document.createElement('div'); // creates cell
cell.className = 'cell';
cell.textContent = (i + 1) + '-' + (j + 1); // sets text in cell
column.appendChild(cell); // appends cell to column (as row)
}
grid.appendChild(column); // appends column to grid
}
document.body.appendChild(grid); // appends grid to webpage
</script>
</body>
</html>