Home  >  Q&A  >  body text

Count the number of class names to 3 digits through a for loop (001~100) in SCSS (SASS)

How to compile $i to "3 digits"?

@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 this way: https://www.sassmeister.com/gist/7581995

so: .bg-image#{" d" % $i}

But an error occurred in webstorm.

Are there any other good methods? thanks for your help.

P粉428986744P粉428986744220 days ago433

reply all(1)I'll reply

  • P粉449281068

    P粉4492810682024-04-05 10:13:07

    https://www.sassmeister.com/gist/7581995 In this way, This is an issue with spacing during the build process.

    This is how I solved it:

    @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'); }
    }

    reply
    0
  • Cancelreply