Decimal places breaking @while in Sass

718 views Asked by At

Trying to create some classes to define opacity with the following code:

$i : 0;
@while $i <= 1 {
  .opacity-#{$i*100} {
    opacity: $i !important;
  }
  $i : $i + 0.1;
}

But I get the following error:

Invalid CSS after ".opacity-30.": expected class name, was "0"

Looks like it's adding a period after while... not sure what might be causing this.

Using Sass 3.4.14

Using Compass

Any ideas?

Thanks!

1

There are 1 answers

1
Fabrizio Calderan On BEST ANSWER

It seems you need to round the number in the class name: if you print /* #{$i*100} */ the compiler will compute both 30.0, 90.0 and 100.0

So you may use round() function (reference) to get rid of any decimals

$i : 0;
@while $i <= 1 {

   /* #{$i*100} */
  .opacity-#{round($i*100)} {
    opacity: $i !important;
  }

  $i : $i + 0.1;
}

The resulting output (tested on sassmeister) is

/* 0 */
.opacity-0 { opacity: 0 !important; }

/* 10 */
.opacity-10 { opacity: 0.1 !important; }

/* 20 */
.opacity-20 { opacity: 0.2 !important; }

/* 30.0 */
.opacity-30 { opacity: 0.3 !important; }

/* 40 */
.opacity-40 { opacity: 0.4 !important; }

/* 50 */
.opacity-50 { opacity: 0.5 !important; }

/* 60 */
.opacity-60 { opacity: 0.6 !important; }

/* 70 */
.opacity-70 { opacity: 0.7 !important; }

/* 80 */
.opacity-80 { opacity: 0.8 !important; }

/* 90.0 */
.opacity-90 { opacity: 0.9 !important; }

/* 100.0 */
.opacity-100 { opacity: 1.0 !important; }