Lovelock
Lovelock

Reputation: 8085

SASS Interpolation within loop converting increment to string

I have a SASS loop to create to create some utility classes:

@for $i from 1 through 10 {
    &border-white-#{($i * 10)} {
        border-color: color($color-white, #{$i / 10});
    }
}

This color function sets the RGBA alpha value but SASS is currently saying that the alpha value must be an integer but a string is provided.

When checking the type_of the value it shows string.

How can I convert this interpolated value to an integer?

Upvotes: 0

Views: 419

Answers (2)

Mark Witmer
Mark Witmer

Reputation: 128

Remove the #{} within the "color($color-white, #{$i / 10});" . It's not needed at that point since you're not outputting that value to a native CSS function. I'd also suggest using sassmeister.com for quick Sass debugging.

Assumptions in this answer:

  • The Color function is your custom sass function which uses Sass's RGBA function.

Upvotes: 3

SuperDJ
SuperDJ

Reputation: 7661

I have the following function that should convert a string to a integer. The function seems to come from: https://codepen.io/corysimmons/pen/mVLVbo. However it is written in scss so you might still need to fix some issues:

@function number( $value ) {
    @if type-of( $value ) == 'number' {
        @return $value;
    } @else if type-of( $value ) != 'string' {
        $_: log( 'Value for `to-number` should be a number or a string.' );
    }

    $result: 0;
    $digits: 0;
    $minus: str-slice( $value, 1, 1 ) == '-';
    $numbers: ( '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 );

    @for $i from if( $minus, 2, 1 ) through str-length( $value ) {
        $character: str-slice( $value, $i, $i) ;

        @if not ( index( map-keys( $numbers ), $character ) or $character == '.') {
            @return to-length( if( $minus, -$result, $result ), str-slice( $value, $i ) )
        }

        @if $character == '.' {
            $digits: 1;
        } @else if $digits == 0 {
            $result: $result * 10 + map-get( $numbers, $character );
        } @else {
            $digits: $digits * 10;
            $result: $result + map-get( $numbers, $character ) / $digits;
        }
    }

    @return if( $minus, -$result, $result );
}

However as pointed out. You are already working with integers but are casting it to a string #{$i / 10}.

Just try to repeat of what you already have done.

&border-white-#{($i * 10)} {
     border-color: color($color-white, ($i / 10));
}

The problem with this however may be that RGBA() expects a . notated value for example: rgba(255, 255, 255, .5)

Upvotes: 0

Related Questions