Asna_Siddiqui
Asna_Siddiqui

Reputation: 31

How can I use @for in sass to assign background positions to multiple classes

Ok so here's my code:

.file-icon,.folder-icon{
      $size:24px;
      position: absolute;
      top: 10px;
      left: 44px;
      display: block;
      float: left;
      width: $size;
      height: $size;
      margin-right: 10px;
      background: $driveIcon;

      &.folder-close{
        background-position: 0 -72px;
        &.folder-open{
          background-position: -$size -72px;
        }
      }

      &.archiveIcon{
        background-position: -$size*2 -72px;
      }
      &.audioIcon{
        background-position: -$size*3 -72px;
      }
      &.brokenIcon{
        background-position: -$size*4 -72px;
      }
      &.docIcon{
        background-position: -$size*5 -72px;
      }
      &.imgfile{
        background-position: -$size*6 -72px;
      }
      &.pdfIcon{
        background-position: -$size*7 -72px;
      }
      &.pptx{
        background-position: -$size*8 -72px;
      }
      &.txtIcon{
        background-position: -$size*9 -72px;
      }
      &.unknown{
        background-position: -$size*10 -72px;
      }
      &.videoIcon{
        background-position: -$size*11 -72px;
      }
      &.xlsIcon{
        background-position: -$size*12 -72px;
      }
      &.viewer{
        background-position: -$size*13 -72px;
        &.folder-open{
          background-position: -$size*14 -72px;
        }
      }
      &.owner{
        background-position: -$size*15 -72px;
        &.folder-open{
          background-position: -$size*16 -72px;
        }
      }
      &.moderator{
        background-position: -$size*17 -72px;
        &.folder-open{
          background-position: -$size*18 -72px;
        }
      }
    }

What I want to do is automate this assigning of background positioning. I tried using @for for the actual statement but not able to figure out how to assign the results one by one to my custom second classes. Please help me out, i'm a beginner in sass. Thankyou.

This is what I've done up till now:

@for $i from 0 to 18{ background-position: -($size*$i} -72px; }

Upvotes: 2

Views: 61

Answers (1)

Mario Araque
Mario Araque

Reputation: 4572

Well, you can use sass lists for your sprites.

Here is an approach:

$list: archiveIcon, audioIcon;
$size: 24px;
$totalClasess: 2;
@each $value in $list {
  &.#{$value} {
    background-position: -($size*$totalClasses) -72px;

    @if $value == folder-close {
      &.folder-open {
        background-position: -$size -72px;
      }
    }
  }
  $totalClasses: $totalClasses + 1;
}

You have to complete the list with all your classes.

Regards.

Upvotes: 1

Related Questions