Search code examples
csscss-gridmultiple-columns

How to wrap a css grid in both column and a certain amount of rows, while following logical alphabetical order?


So i have a grid setup like this

<div class="grid-container">
  <div>a</div>
  <div>b</div>
  <div>c</div>
  <div>d</div>
  <div>e</div>
  <div>f</div>
  ...
  <div>z</div>
</div>

How can i make it appear in two columns, grouped in rows of say 4 high. Creating an arrangement like this:

a | e
b | f
c | g
d | h
----- 
i | m
j | n

...

s | w
t | x
----- 
y |
z |

Without the obvious answer of grouping 4 or 8 divs to a separate gridbox. Implementations that differ from using divs are welcome too

I currently got it semi working except for the alphabetical sorting by using

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 150px);
  grid-template-rows: repeat(4, auto);
}

.grid-container DIV:nth-child(8n) {
  padding-bottom: 10px;
}

But that does not honor the alphabetical order, giving this:

a | b
c | d
e | f
g | h
-----
i | j

Adding

grid-auto-flow: column;

to the container makes it add more columns on overflow, disregarding the defined 2 columns.


Solution

  • You have a pattern that repeats each 8 elements so:

    .grid-container {
      display: grid;
      gap: 5px;
      justify-content: start;
      grid-auto-flow: dense;
    }
    .grid-container :nth-child(8n + 1),
    .grid-container :nth-child(8n + 2),
    .grid-container :nth-child(8n + 3),
    .grid-container :nth-child(8n + 4) {
      grid-column: 1;
    }
    .grid-container :nth-child(8n + 5),
    .grid-container :nth-child(8n + 6),
    .grid-container :nth-child(8n + 7),
    .grid-container :nth-child(8n + 8) {
      grid-column: 2;
    }
    
    .grid-container :nth-child(8n + 8) {
      margin-bottom: 5px;
    }
    <div class="grid-container">
      <div>a</div>
      <div>b</div>
      <div>c</div>
      <div>d</div>
      <div>e</div>
      <div>f</div>
      <div>g</div>
      <div>h</div>
      <div>i</div>
      <div>j</div>
      <div>k</div>
      <div>l</div>
      <div>m</div>
      <div>n</div>
      <div>o</div>
      <div>p</div>
      <div>q</div>
      <div>r</div>
    </div>

    And with some optimization:

    .grid-container {
      display: grid;
      gap: 5px;
      justify-content: start;
      grid-auto-flow: dense;
    }
    .grid-container > * {
      grid-column: 1;
    }
    .grid-container :is(:nth-child(8n + 5),:nth-child(8n + 6),:nth-child(8n + 7),:nth-child(8n)) {
      grid-column: 2;
    }
    
    .grid-container :nth-child(8n) {
      margin-bottom: 5px;
    }
    <div class="grid-container">
      <div>a</div>
      <div>b</div>
      <div>c</div>
      <div>d</div>
      <div>e</div>
      <div>f</div>
      <div>g</div>
      <div>h</div>
      <div>i</div>
      <div>j</div>
      <div>k</div>
      <div>l</div>
      <div>m</div>
      <div>n</div>
      <div>o</div>
      <div>p</div>
      <div>q</div>
      <div>r</div>
    </div>