循环数组Sass并创建CSS

时间:2019-06-18 13:06:38

标签: sass compass-sass scss-mixins

我像这样在sass中有一个功能

$positions: left top bottom right;
$short-paddings: lp tp bp rp;
@each $current-position in $positions {
  $i: index($positions, $current-position);
  @for $x from 1 through 2 {
     @each $current-short in $short-paddings{
      .#{$current-short}-#{$x} {
        padding-#{$current-position}: #{$x}px !important;

      }
    }
  }
}

当我输出时,我得到了一些东西

.pl-1 {
  padding-left: 1px !important;
}

.pt-1 {
  padding-left: 1px !important;
}

.pb-1 {
  padding-left: 1px !important;
}

.pr-1 {
  padding-left: 1px !important;
}

.pl-2 {
  padding-left: 2px !important;
}

.pt-2 {
  padding-left: 2px !important;
}

.pb-2 {
  padding-left: 2px !important;
}

.pr-2 {
  padding-left: 2px !important;
}

.pl-1 {
  padding-top: 1px !important;
}

.pt-1 {
  padding-top: 1px !important;
}

.pb-1 {
  padding-top: 1px !important;
}

.pr-1 {
  padding-top: 1px !important;
}

.pl-2 {
  padding-top: 2px !important;
}

.pt-2 {
  padding-top: 2px !important;
}

.pb-2 {
  padding-top: 2px !important;
}

.pr-2 {
  padding-top: 2px !important;
}

.pl-1 {
  padding-bottom: 1px !important;
}

.pt-1 {
  padding-bottom: 1px !important;
}

.pb-1 {
  padding-bottom: 1px !important;
}

.pr-1 {
  padding-bottom: 1px !important;
}

.pl-2 {
  padding-bottom: 2px !important;
}

.pt-2 {
  padding-bottom: 2px !important;
}

.pb-2 {
  padding-bottom: 2px !important;
}

.pr-2 {
  padding-bottom: 2px !important;
}

.pl-1 {
  padding-right: 1px !important;
}

.pt-1 {
  padding-right: 1px !important;
}

.pb-1 {
  padding-right: 1px !important;
}

.pr-1 {
  padding-right: 1px !important;
}

.pl-2 {
  padding-right: 2px !important;
}

.pt-2 {
  padding-right: 2px !important;
}

.pb-2 {
  padding-right: 2px !important;
}

.pr-2 {
  padding-right: 2px !important;
}

但是有一些错误的CSS,我需要输出的是我在最终的CSS中会得到一些= this

.pl-1 {
  padding-left: 1px !important;
}

.pt-1 {
  padding-top: 1px !important;
}

.pb-1 {
  padding-bottom: 1px !important;
}

.pr-1 {
  padding-right: 1px !important;
}

.pl-2 {
  padding-left: 2px !important;
}

.pt-2 {
  padding-top: 2px !important;
}

.pb-2 {
  padding-bottom: 2px !important;
}

.pr-2 {
  padding-right: 2px !important;
}

知道我在哪里做错了吗?

1 个答案:

答案 0 :(得分:1)

第一个循环@each $current-position in $positions引起了您的问题。您可以删除它并通过地图实现所需的功能:

$short-paddings: (
  top: 'pt',
  left: 'pl',
  bottom: 'pb',
  right: 'pr'
);

@for $i from 1 through 2 {
  @each $position, $prefix in $short-paddings {
    .#{$prefix}-#{$i} {
      padding-#{$position}: #{$i}px !important;
    }
  }
}

SASS Maps documentation