定义scss的外边距内边距,通过四个方向分别定义一个 SCSS @mixin,并利用 @for 循环生成四组样式

85 阅读1分钟
//定义外边距
// 定义通用的外边距 mixin
@mixin setMargin($direction, $value) {
  margin-#{$direction}: #{$value}px;
}

// 生成四个方向的样式
@for $i from 1 through 100 {
  // 上边距
  $topSelector: unquote("mar-top#{$i}");
  .#{$topSelector} {
    @include setMargin(top, $i);
  }

  // 下边距
  $bottomSelector: unquote("mar-bottom#{$i}");
  .#{$bottomSelector} {
    @include setMargin(bottom, $i);
  }

  // 左边距
  $leftSelector: unquote("mar-left#{$i}");
  .#{$leftSelector} {
    @include setMargin(left, $i);
  }

  // 右边距
  $rightSelector: unquote("mar-right#{$i}");
  .#{$rightSelector} {
    @include setMargin(right, $i);
  }
}

//定义内边距
// 定义通用的内边距 mixin
@mixin setMargin($direction, $value) {
  padding-#{$direction}: #{$value}px;
}

// 生成四个方向的样式
@for $i from 1 through 100 {
  // 上边距
  $topSelector: unquote("pad-top#{$i}");
  .#{$topSelector} {
    @include setMargin(top, $i);
  }

  // 下边距
  $bottomSelector: unquote("pad-bottom#{$i}");
  .#{$bottomSelector} {
    @include setMargin(bottom, $i);
  }

  // 左边距
  $leftSelector: unquote("pad-left#{$i}");
  .#{$leftSelector} {
    @include setMargin(left, $i);
  }

  // 右边距
  $rightSelector: unquote("pad-right#{$i}");
  .#{$rightSelector} {
    @include setMargin(right, $i);
  }
}


在html中用法是
<div class="mar-top20 pad-top20">边距</div> 


// 动态生成 font-size 类
@for $i from 10 through 50 { // 字体大小范围 10px 到 50px
  .fontS#{$i}px {
    font-size: #{$i}px;
  }
}

// 动态生成颜色类
$colors: (
  "900": #900,
  "f00": #f00,
  "0f0": #0f0,
  "00f": #00f
);

@each $name, $color in $colors {
  .cl##{$name} {
    color: #{$color};
  }
}

在html中用法是
<p class="fontS20px cl#900">字体大小是20px,颜色是#900</p> 
<p class="fontS15px cl#f00">字体大小是15px,颜色是#f00</p>