'How to create a TailwindCSS grid with a dynamic amount of grid columns?

I'm using Vue3 with TailwindCSS and want to create a grid with a dynamic grid-cols-{n} class. I know that TailwindCSS supports up to 12 columns by default but I can't customize the theme because the amount of columns is completely dynamic.

Given the following plain HTML / Js example

const amountOfItemsPerRow = 16;

const container = document.getElementById("container");

for (let i = 0; i < amountOfItemsPerRow; i++) {
  const item = document.createElement("div");
  item.innerText = i;
  container.appendChild(item);
}

container.classList.add(`grid-cols-${amountOfItemsPerRow}`); // this doesn't work if the value is greater than 12
<script src="https://cdn.tailwindcss.com"></script>

<div id="container" class="grid"></div>

This code works fine if amountOfItemsPerRow is smaller or equal than 12, otherwise the CSS is broken.

Do I have to write code to setup plain CSS solving this or is there a dynamic Tailwind solution?


Another approach:

Based on the docs I tried to replace the line

container.classList.add(`grid-cols-${amountOfItemsPerRow}`);

with

container.classList.add(`grid-template-columns:repeat(${amountOfItemsPerRow},minmax(0,1fr))`);

to come up with a "native" approach but that didn't help.



Solution 1:[1]

Create Dynamic Class Name with Tailwindcss is easy. Inside [ and ], You can add Dynamic Class with TailwindCSS

const amountOfRows = 16;
const amountOfCellsPerRow = 16;

const container = document.getElementById("container");

for (let rowIndex = 0; rowIndex < amountOfRows; rowIndex++) {
  for (let columnIndex = 0; columnIndex < amountOfCellsPerRow; columnIndex++) {
    const cell = document.createElement("div");
    cell.innerText = rowIndex + "|" + columnIndex;
    container.appendChild(cell);
  }
}

container.classList.add(`grid-cols-[${amountOfCellsPerRow}]`)

For more details here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ajay Raja