Luc
Luc

Reputation: 1825

Sass control directive with decimal numbers

I'm trying to get a sass function going:

$times: 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.75 0.80 0.90;

@each $value in $times{
  .is-hidden-#{$value}{
    @include hide( $value + s );
  }
}

The problem is this: somehow, it doesn't accept decimal numbers. It works perfectly with 1, 2, 3, etc. I even tried this:

$times: 10 20 30 40 50 60 70 80 90;

@each $value in $times{
  .is-hidden-#{$value}{
    @include hide( ($value / 100) + s );
  }
}

But sass doesn't do anything with that last calculation there. He just ignores the '/ 100'. Is there some way I can pass decimal numbers through a function like this? The output would be this:

.is-hidden-0.1s{

}

.is-hidden-0.2s{

}

.is-hidden-0.3s{

}

etc....

Thanks!

--- EDIT --- This is the hide mixin:

@mixin hide( $time ){
  opacity: 0;
  visibility: hidden;
  @include transition( $time );
}

Upvotes: 2

Views: 1384

Answers (2)

Ben West
Ben West

Reputation: 4596

Here's a general way to escape decimal numbers for class names (replacing . with -)

@function strip-units ( $number ) {
    @return $number / ( $number * 0 + 1 );
}

@function escape-number ( $value ) {
    @if type-of( $value ) != 'number' {
        @return $value;
    }
    $int: floor( strip-units( $value ) );
    $fract: $value - $int;
    @if ( $fract == 0 ) {
        @return $int;
    }
    @while ( $fract != floor( $fract ) ) {
        $fract: $fract * 10;
    }
    @return $int + '-' + $fract;
}

Upvotes: 1

cimmanon
cimmanon

Reputation: 68339

Your desired output is invalid CSS. From the CSS validator:

In CSS1, a class name could start with a digit (".55ft"), unless it was a dimension (".55in"). In CSS2, such classes are parsed as unknown dimensions (to allow for future additions of new units) To make "1s" a valid class, CSS2 requires the first digit to be escaped ".\31s" [1s]

There are many times where Sass will give you errors when you try to generate invalid CSS. To generate valid results, you need to compose the selector using integers and adding the escaped decimal point like this:

@for $i from 1 through 9 {
  .is-hidden-0\.#{$i}s {
    @include hide($i / 10 * 1s);
  }
}

Upvotes: 2

Related Questions