【问题标题】:How To Dynamically Build Grid-Area-Templates of (n x n) Grid Using SASS function如何使用 SASS 函数动态构建 (n x n) 网格的网格区域模板
【发布时间】:2020-12-17 18:31:13
【问题描述】:

我已将以下 CSS grid-area-templates 硬编码为 5x5 网格:

  #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"
  }

但是我想要多种尺寸的网格,并且我想动态构建它们。因此,我想编写一个函数来接收ji,这样:

@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)
}

我尝试过使用 @for@mixin 变体,但到目前为止还很难做到这一点

【问题讨论】:

    标签: css sass css-grid


    【解决方案1】:

    以下是生成网格的方法:

    @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);
    }
    

    但是,它会在一行中生成模板:

    #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" [...];
    }
    

    据我所知,此代码仍然有效。我不确定是否可以使用 SCSS 在多行上生成多个字符串。

    【讨论】:

      【解决方案2】:

      在这里你也可以这样做

      @function buildGrid($j, $i) {
          $result: "";
          @for $cur from $j - $i to $j {
              $result2: "";
      
              @for $current from $j - $i to $j {
                  @if($result2 == "") {
                      $result2: #{$cur}-#{$current};
                  } @else {
                      $result2: append($result2, #{$cur}-#{$current});
                  }
              }
      
              @if($result == "") {
                  $result: "#{$result2}";
              } @else {
                  $result: append($result, "#{$result2}");
              }
          }
          @return $result;
      }
      
      #grid-small {
          grid-template-areas: buildGrid(5, 5)
      }
      
      #grid-large {
        grid-template-areas: buildGrid(25,25);
      }
      
      

      【讨论】:

      • 您可以使用to 而不是through 来排除循环中的最终数字,因此您不必执行$var - 1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2011-05-12
      • 1970-01-01
      • 2020-02-04
      相关资源
      最近更新 更多