首页 文章

动态类和值

提问于
浏览
0

所有方向都有以下辅助类(包括边距和填充):

.h-space-top-10 {margin-top: 10px;}
.h-space-top-20 {margin-top: 20px;}
.h-space-top-30 {margin-top: 30px;}

反正有没有用Sass创建具有动态值的那些(例如,高达10x基值10px)或者是否必须手动将它们写出来?

3 回答

  • 0
    @for $i from 1 through 3 {.h-space-top-#{$i * 10} {margin-top:#{$i * 10}px}}
    
  • 0
    $properties: (margin padding);
    $positions: (top right bottom left);
    $range: 10;
    
    @each $property in $properties  {
      @each $item in $positions  {
        @for $ii from 1 through $range {
            .h-#{$property}-#{$item}-#{$ii * 10} { #{$property}-#{$item}: #{$ii * 10}px; }
        }
      }
    }
    
  • 1

    您可以定义两个变量:重复次数和每次重复跳转的px数 . 像这样的东西:

    $numRepetitions: 3;
    $pxJump: 10;
    
    @for $i from 1 through $numRepetitions {
        .h-space-top-#{$i * $pxJump} {
                margin-top:#{$i * $pxJump}px
        }
    }
    

    该案例的输出将是您需要的代码:

    .h-space-top-10 {
      margin-top: 10px;
    }
    
    .h-space-top-20 {
      margin-top: 20px;
    }
    
    .h-space-top-30 {
      margin-top: 30px;
    }
    

    但是,如果您需要例如迭代4次并在每次跳转中求和5px,您只需要更改变量的值,如下所示:

    $numRepetitions: 4; //4 instead of 3 repetitions
    $pxJump: 5; //5px instead of 10px
    
    @for $i from 1 through $numRepetitions {
        .h-space-top-#{$i * $pxJump} {
                margin-top:#{$i * $pxJump}px
        }
    }
    

    在这种情况下,您将获得此代码:

    .h-space-top-5 {
      margin-top: 5px;
    }
    
    .h-space-top-10 {
      margin-top: 10px;
    }
    
    .h-space-top-15 {
      margin-top: 15px;
    }
    
    .h-space-top-20 {
      margin-top: 20px;
    }
    

相关问题