Search code examples
csscss-grid

Is it possible to make a table which has different rows for each column via gird box?


enter image description here

Can I use grid-box to achieve the layout of this table?

I know that if the rows for each column is a times to each other, it will be possible.

I am not sure if I can use grid-box to make a table which has different number of rows in each column and the number are not times of each other.


Solution

  • There are multiple ways to achieve the desired layout using CSS Grid. The trick is to have the grid items in the first column to span multiple rows to allow the grid items in the second and third columns to be aligned in the middle of the grid item that is placed at second row, first column.

    The following example uses grid-template-areas to achieve the desired output:

    .grid-container {
      display: grid;
      height: 300px;
      grid-gap: 3px;
      grid-template-rows: repeat(6, 1fr);
      grid-template-areas: 
        "sm1 wd1 wd2" 
        "sm1 wd1 wd2" 
        "sm2 wd1 wd2" 
        "sm2 wd3 wd4" 
        "sm3 wd3 wd4" 
        "sm3 wd3 wd4";
    }
    
    .grid-item {
      background: #999;
    }
    
    .grid-item:nth-of-type(1) { grid-area: sm1; }
    .grid-item:nth-of-type(2) { grid-area: wd1; }
    .grid-item:nth-of-type(3) { grid-area: wd2; }
    .grid-item:nth-of-type(4) { grid-area: sm2; }
    .grid-item:nth-of-type(5) { grid-area: wd3; }
    .grid-item:nth-of-type(6) { grid-area: wd4; }
    .grid-item:nth-of-type(7) { grid-area: sm3; }
    <div class="grid-container">
      <div class="grid-item"></div>
      <div class="grid-item"></div>
      <div class="grid-item"></div>
      <div class="grid-item"></div>
      <div class="grid-item"></div>
      <div class="grid-item"></div>
      <div class="grid-item"></div>
    </div>