generate css grid in javascript

To generate a CSS grid using JavaScript, you can follow these steps:

  1. Create a parent container element in HTML where you want to display the grid.
<div class="grid-container"></div>
35 chars
2 lines
  1. Use JavaScript to select the container and create individual grid items dynamically, and add them to the container.
index.tsx
const container = document.querySelector('.grid-container');
const numberOfItems = 12; // number of grid items you want to create

for (let i = 0; i < numberOfItems; i++) {
    const gridItem = document.createElement('div');
    gridItem.classList.add('grid-item');
    container.appendChild(gridItem);
}
305 chars
9 lines
  1. Define the CSS grid layout properties on the container element using JavaScript, such as the number of columns and rows, and the size of the grid items. You can also set other properties like gap, alignment, etc.
index.tsx
const gridColumns = 3;
const gridRows = Math.ceil(numberOfItems / gridColumns);
container.style.display = 'grid';
container.style.gridTemplateColumns = `repeat(${gridColumns}, 1fr)`;
container.style.gridTemplateRows = `repeat(${gridRows}, 1fr)`;
container.style.gridGap = '10px';

const gridItems = document.querySelectorAll('.grid-item');
gridItems.forEach(item => {
    item.style.width = '100%';
    item.style.height = '100%';
});
435 chars
13 lines

This will generate a responsive CSS grid layout on your web page, with the number of items and layout properties defined in JavaScript.

gistlibby LogSnag