Search code examples
sasscompass-sassscss-mixins

Loop array sass and create css


I have one function in sass like this

$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;

      }
    }
  }
}

When i do output i got something this

.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;
}

But there some wrong css what i need to output is that i in final css i will have something =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;
}

Any idea where i am doing wrong?


Solution

  • The first loop @each $current-position in $positions is causing your problem. You can remove it and achieve what you want with a map:

    $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