Search code examples
htmlcsssyntaxcss-grid

Looking a more terse syntax for repeating columns of a pattern using css grid?


Is there any syntax for repeating this exact grid layout?

.grid-system {    
  grid-template-columns: 42px 48px 42px 48px 42px 48px 42px 48px 42px 48px 42px;
}

I tried but it seemingly didn't work:

.grid-system {    
  grid-template-columns: repeat(11, 42px, 48px);
}

Here's a code pen with more details:

https://codepen.io/matthewharwood/pen/vPXWmm

As you can see the design breaks the default grid system so I made a flattened grid (samba-flat-grid) w/o gaps to compensate: enter image description here


Solution

  • It is grid-template-columns: repeat(11, 42px 48px) - without the space between them. Check here for all the possibilities.

    See demo below:

    .samba-grid {
      display: grid;
      grid-template-columns: repeat(12, 42px);
      background: pink;
      width: 100%;
      column-gap: 48px;
    }
    
    .samba-flat-grid {
      display: grid;
      grid-template-columns: repeat(11, 42px 48px); /* CHANGED */
      background: yellow;
      width: 100%;
    }
    
    .container {
      width: 100%;
      max-width: 1032px;
      margin: 0 auto;
      background: green;
    }
    
    .section {
      width: 100%;
      display: block;
      background: papayawhip;
    }
    
    .element-1 {
      grid-column-start: 1;
      grid-column-end: span 6;
    }
    
    .element-2 {
      grid-column-start: 7;
      grid-column-end: span 6;
    }
    
    .element-inner-img {
      background: blue;
      grid-column-start: 1;
      grid-column-end: span 6;
    }
    
    .element-inner-img img {
      width: 100%;
    }
    
    .element-inner-content {
      background: #b000b5;
      grid-column-start: 7;
      grid-column-end: 12;
    }
    <div class="section">
      <div class="container">
        <div class="samba-grid">
          <div class="element-1">
            <div class="samba-flat-grid">
              <div class="element-inner-img">
                <img src="https://placebear.com/1600/900" alt="">
              </div>
              <div class="element-inner-content">
                <p>Hello World</p>
              </div>
            </div>
          </div>
          <div class="element-2">
    
            <div class="samba-flat-grid">
              <div class="element-inner-img">
                <img src="https://placebear.com/1600/900" alt="">
              </div>
              <div class="element-inner-content">
                <p>Hello World</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>