count the number of class names to 3 digits via a for-loop(001~100) in SCSS(SASS)

41 Views Asked by At

How can I compile $i to '3 digit number'?

@for $i from 1 through 100 {
  .bg-image#{$i} {
    background-image: url("folder/bg-image#{$i}.jpg");
  }
}

I want it to compile like this.

.bg-image001 {
  background-image: url("folder/bg-image001.jpg");
}
.bg-image002 {
  background-image: url("folder/bg-image002.jpg");
}
...
.bg-image099 {
  background-image: url("folder/bg-image099.jpg");
}
.bg-image100 {
  background-image: url("folder/bg-image100.jpg");
}

I tried to this way: https://www.sassmeister.com/gist/7581995

and this way: .bg-image#{"%03d" % $i}

but it got error in webstorm.

errors

Are there any other good methods? Thank you for your help.

1

There are 1 best solutions below

0
Syoki On

https://www.sassmeister.com/gist/7581995 In this way, it was a problem that spacing occurred during build.

I solved it like this:

@function zerofill($i) {
  @return #{str-slice("000",0,3 - str-length(#{$i}))}+$i;
}

@for $i from 1 through 100 {
  $i: zerofill($i);
  #layer-#{$i} { background: url('../layers/layer-#{$i}.png'); }
}