title: Create dynamic class names using @while loop
body: <p>I want to create the following in a stylesheet using SASS:</p>
  
  <pre><code>.dC1, .dC2, .dC3 {
      color: white;
  }
  .dC4, .dC5 {
      color: black;
  }
  </code></pre>
  
  <p>using a @while loop in SASS such as the following (I know it's a bit off, I will refine it once I figure out how to set it up):</p>
  
  <pre><code>$i: 1;
  $whiteLevel: 3;
  $blackLevel: 5;
  $val: nil;
  
  @while $i &lt;= $whiteLevel {
      $val: $val + .dC#{$i};
      $i: $i + 1;
  }
  
  $val {
      color: white;
  }
  
  $val: nil;
  
  @while $i &gt; $whiteLevel and $i &lt;= $blackLevel {
      $val: $val + .dC#{$i};
      $i: $i + 1;
  }
  
  $val {
      color: black;
  }
  </code></pre>
  
  <p>Yes, I know it's ugly as sin but I think it gets across what I want. Ultimately the $whiteLevel and $blackLevel (or whateever I end up calling them) will be in a _base.scss file so I can change the different levels and number of classes "on the fly."</p>
  
  <p>Is it possible to do it and can someone point me in the right direction?</p>
  
  <p>Thanks in advance and looking forward to hearing any suggestions!</p>
  
  <p>Edit: To clarify I can use the following code to get the same result:</p>
  
  <pre><code>$whiteLevel: 3;
  
  .cW {
      color: white;
  }
  
  .cB {
      color: black;
  }
  
  @for $i from 1 through 5{
      .dC#{$i} {
          @if $i &lt;= $whiteLevel {
              @extend .cW;
          } @else {
              @extend .cB;
          }
      }
  }
  </code></pre>
  
  <p>This produces:</p>
  
  <pre><code>.cW, .dC1, .dC2, .dC3 {
      color: white;
  }
  
  .cB, .dC4, .dC5 {
      color: black;
  }
  </code></pre>
  
  <p>Which is the 99% solution, but it means I have to have a specific class already built to accomodate the @extend. My goal is to make this totally dynamic and dependent on the values of $whiteLevel and $blackLevel. If I set them to 0 I want to make it so no class is created.</p>
  
  <p>Hope that helps clarify a bit.</p>
  
  <p><strong>Edit edit!</strong></p>
  
  <p>Thanks to cimmanon here is the solution I will using (based on provided solution, gotta love that % sign):</p>
  
  <pre><code>$whiteLevel: 3;
  
  %cW {
      color: white;
  }
  
  %cB {
      color: black;
  }
  
  @for $i from 1 through 5{
      .dC#{$i} {
          @if $i &lt;= $whiteLevel {
              @extend %cW;
          } @else {
              @extend %cB;
          }
      }
  }
  </code></pre>
  
  <p>Many thanks cimmanon!</p>