Search code examples
htmlcsscss-grid

Creating a specific CSS grid with an unlimited number of elements


I trying to create a CSS grid that will have specific columns (row by row) where I can add any number of DIVs, which will be added in specific order:

[1] [2] [3]
[4] [5]
[6] [7] [8]
[9] [10]
etc

But also I want to be able to access the div of each "subgroup" (1-3, 5-8, 4-5, 9-10 etc) to edit their "insides" by CSS

Any help would be appreciated.

I tried to use grid-template-columns, but all I've achieved is displaying elements three in a row via repeat(3, 1fr)


Solution

  • Consider a 6 columns configuration:

    .container {
      display: grid;
      grid-template-columns:repeat(6,1fr);
      gap: 10px;
    }
    
    .container > div {
      grid-column: span 2;
      background: red;
      height: 50px;
    }
    .container > div:is(:nth-child(5n + 4),:nth-child(5n)) {
      grid-column: span 3;
      background: blue;
    }
    <div class="container">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>