Search code examples
csssasscss-grid

How To Dynamically Build Grid-Area-Templates of (n x n) Grid Using SASS function


I have hardcoded the following CSS grid-area-templates for a 5x5 grid:

  #grid {
    grid-template-areas:
      "0-0 0-1 0-2 0-3 0-4"
      "1-0 1-1 1-2 1-3 1-4"
      "2-0 2-1 2-2 2-3 2-4"
      "3-0 3-1 3-2 3-3 3-4"
      "4-0 4-1 4-2 4-3 4-4"
  }

However I want grids of multiple sizes and i'd like to dynamically build them. Because of this, I'd like to write a function that will take in j and i such that:

@function buildGrd(j,i) {
  @return // [snip]
}

// @buildGrid(5,5) =>
"0-0 0-1 0-2 0-3 0-4"
"1-0 1-1 1-2 1-3 1-4"
"2-0 2-1 2-2 2-3 2-4"
"3-0 3-1 3-2 3-3 3-4"
"4-0 4-1 4-2 4-3 4-4"

#grid-small {
  grid-template-areas: @buildGrid(5,5)
}

#grid-large {
  grid-template-areas: @buildGrid(25,25)
}

I've tried using @for and @mixin variations but struggled to do this so far


Solution

  • Here is how you can generate your grids:

    @function buildGrid($j, $i) {
        $template: null;
        
        @for $x from 0 to $j {
            $string: '';
            
            @for $y from 0 to $i {
                @if $y > 0 { $string: $string + ' '; }
                $string: $string + $x + "-" + $y;
            }
            
            $template: $template $string;
        }
        
      @return $template;
    }
    
    #grid-small {
      grid-template-areas: buildGrid(5,5);
    }
    
    #grid-large {
      grid-template-areas: buildGrid(25,25);
    }
    

    However, it will generate the template on a single line as:

    #grid-small {
      grid-template-areas: "0-0 0-1 0-2 0-3 0-4" "1-0 1-1 1-2 1-3 1-4" "2-0 2-1 2-2 2-3 2-4" [...];
    }
    

    As far as I know, this code is still valid though. I'm not sure it's possible to generate multiple strings on multiple lines with SCSS.