less的each生成批量间距

529 阅读1分钟

习惯了bootstrap的那套全局间距样式,之前用的是scss,网上的方法很多,这次项目改用less,找了很久,终于找到each的嵌套用法 点击查看

话不多说,直接上代码。

less版

// 批量间距
@spacing-base-size: 1rem;
.spacing-types(){
        m: margin;
        p: padding;
};
.spacing-direction() {
        t: top;
        r: right;
        b: bottom;
        l: left;
};
.spacing-sizes() {
      0: 0; 
      1: 0.625;//10px
      2: 1.25;//20px
      3: 1.875;//30px
      4: 2.5;//40px
      5: 3.125;//50px
      6: 0.37;//6px
};
each(.spacing-types(),.(@type,@typeKey){
  each(.spacing-sizes(),.(@size,@sizeKey){
    // 四周间距 m/p-0/1/2/3/4/5
    .@{typeKey}-@{sizeKey}{
      @{type}: @size * @spacing-base-size
    };
    // 横向间距 mx/px-0/1/2/3/4/5
    .@{typeKey}x-@{sizeKey}{
      @{type}-left:@size * @spacing-base-size;
      @{type}-right:@size * @spacing-base-size;
    };
    // 纵向间距 my/py-0/1/2/3/4/5
    .@{typeKey}y-@{sizeKey}{
      @{type}-top:@size * @spacing-base-size;
      @{type}-bottom:@size * @spacing-base-size;
    };
    // 单向间距 mt/mr/mb/ml/pt/pr/pb/pl-0/1/2/3/4/5
    each(.spacing-direction(),.(@dir,@dirKey){
      .@{typeKey}@{dirKey}-@{sizeKey}{
        @{type}-@{dir}: @size * @spacing-base-size;
      };
    });
  });
});

scss版

// 批量间距
$spacing-types: (
  m: margin,
  p: padding
);
$spacing-direction: (
  t: top,
  r: right,
  b: bottom,
  l: left
);
$spacing-base-size: 1rem;
$spacing-sizes: (
  0: 0,
  1: 0.625,
  2: 1.25,
  3: 1.875,
  4: 2.5,
  5: 3.125,
  6: 0.375
);
@each $typeKey, $type in $spacing-types {
  //m-0
  @each $sizeKey, $size in $spacing-sizes {
    .#{$typeKey}-#{$sizeKey} {
      #{$type}: $size * $spacing-base-size !important;
    }
  }
  //mx-0
  @each $sizeKey, $size in $spacing-sizes {
    .#{$typeKey}x-#{$sizeKey} {
      #{$type}-left: $size * $spacing-base-size !important;
      #{$type}-right: $size * $spacing-base-size !important;
    }
  }
  //my-0
  @each $sizeKey, $size in $spacing-sizes {
    .#{$typeKey}y-#{$sizeKey} {
      #{$type}-top: $size * $spacing-base-size !important;
      #{$type}-bottom: $size * $spacing-base-size !important;
    }
  }
  //mt-0,mb-0,ml-0,mr-0
  @each $dirKey, $dir in $spacing-direction {
    @each $sizeKey, $size in $spacing-sizes {
      .#{$typeKey}#{$dirKey}-#{$sizeKey} {
        #{$type}-#{$dir}: $size * $spacing-base-size !important;
      }
    }
  }
}