Languages
[Edit]
EN

JavaScript - dynamically create grid of divs using flexbox

3 points
Created by:
Brandy-Mccabe
754

In this article, we would like to show you how to dynamically create a grid of HTML div elements using JavaScript.

Dynamically created grid using flexbox in JavaScript.
Dynamically created grid using flexbox in JavaScript.

Practical example

In order to create the grid, we need to take the following steps:

  1. create grid container to store cells/rows/columns,
  2. set the grid element's display property value to flex,
  3. set the column element's flex property value to 1,
  4. 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>

 

See also

  1. HTML - create grid using flexbox

References

  1. flex - CSS: Cascading Style Sheets | MDN
  2. Node.appendChild() - Web APIs | MDN
  3. Document.createElement() - Web APIs | MDN

Alternative titles

  1. JavaScript - dynamically create grid of HTML div elements using flex
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join