Search code examples
csscss-grid

How to simplify this grid layout with repeating grid-areas?


I have this grid-structure and struggle to simplify it, since I need unlimited divs. I tried different approchaes with nth-child and grid span, but I just can get it done.

enter image description here

HTML

<div class="parent">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
    <div class="div4">4</div>
    <div class="div5">5</div>
    <div class="div6">6</div>
    <div class="div7">7</div>
    <div class="div8">8</div>
    <div class="div9">9</div>
    <div class="div10">10</div>
    <div class="div11">11</div>
    <div class="div12">12</div>
</div>

CSS

.parent {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(9, 1fr);
    grid-column-gap: 0px;
    grid-row-gap: 0px;
    background:#FFF;
}

.parent div {
    display:flex;
    align-items:center;
    justify-content:center;
    padding:50px;
    border: 1px solid red;
}

.div1 { grid-area: 1 / 1 / 2 / 2; }
.div2 { grid-area: 1 / 2 / 3 / 3; }
.div3 { grid-area: 3 / 2 / 4 / 3; }
.div4 { grid-area: 2 / 1 / 4 / 2; }
.div5 { grid-area: 4 / 1 / 5 / 2; }
.div6 { grid-area: 4 / 2 / 6 / 3; }
.div7 { grid-area: 6 / 2 / 7 / 3; }
.div8 { grid-area: 5 / 1 / 7 / 2; }
.div9 { grid-area: 7 / 1 / 8 / 2; }
.div10 { grid-area: 7 / 2 / 9 / 3; }
.div11 { grid-area: 9 / 2 / 10 / 3; }
.div12 { grid-area: 8 / 1 / 10 / 2; }

Solution

  • Note the repeating pattern.

    This means you only have to define which column and/or how many rows each item is to take for 4 of them.

    Then you use the dense setting on the grid to make sure it always goes back to use spare space.

    Oh, and don't attempt to give an individual class to each item if you have a variable number of items!

    <div class="parent">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      <div>7</div>
      <div>8</div>
      <div>9</div>
      <div>10</div>
      <div>11</div>
      <div>12</div>
    </div>
    <style>
      .parent {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-template-rows: repeat(9, 1fr);
        grid-column-gap: 0px;
        grid-row-gap: 0px;
        background: #FFF;
        grid-auto-flow: dense;
      }
      
      .parent div {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 50px;
        border: 1px solid red;
      }
      
      .parent>div:nth-child(2n) {
        grid-column: 2;
        grid-row: span 2;
      }
      
      .parent>div:nth-child(4n-1) {
        grid-column: 2;
      }
      
      .parent>div:nth-child(4n) {
        grid-row: span 2;
        grid-column: 1;
      }
    </style>