SASS Loop to output classes with unique number and

2019-02-11 03:06发布

问题:

I've stumbled across a situation where a SASS loop would be great. I have a load of <div>'s, each one has the a unique class that follows the pattern of .band-(number), a simplified version of my HTML would look like this...

<div class="band-1"></div>
<div class="band-2"></div>
<div class="band-3"></div>
etc.

Each of these elements has a unique background-image, but the naming convention of the image follows that of the divs themselves. My CSS needs to output this...

.band-1 {
   background-image:url('../img/image_01.png');
}
.band-2 {
   background-image:url('../img/image_02.png');
}
.band-3 {
   background-image:url('../img/image_03.png');
}

How would I go about outputting this in a concise way? Thanks in advance.

回答1:

You can solve your problem with a for loop:

@for $i from 1 through 15 {
  @if $i < 10 {
    .band-#{$i} { 
      background-image:url("../img/image_0#{$i}.png");
    }
  } @else {
    .band-#{$i} { 
      background-image:url("../img/image_#{$i}.png");
    }    
  }
}

DEMO



标签: css loops sass