Hai Tien
Hai Tien

Reputation: 3117

Create class from color code with mixin sass

I want to create a class with a color code, but I cannot split the color code to get only the text without the # character. See my example below:

.background-ccc {
    background:#ccc;
}

I want to use mixin like this:

@mixin background($color){
   $colorwithout: ...get color code without # here...
   .background-#{$colorwithout}{ 
      background:$color;
    }
}

using:

@include background(#ccc)

Upvotes: 0

Views: 479

Answers (1)

Alberto Rhuertas
Alberto Rhuertas

Reputation: 773

Here it goes: Demo

@function str-replace($string, $search, $replace: '') {
    $index: str-index($string, $search);

    @if $index {
        @return str-slice($string, 1, $index - 1)+$replace+str-replace(str-slice($string, $index + str-length($search)),
            $search,
            $replace);
    }

    @return $string;
}

@function to-string($value) {
    @return inspect($value);
}

@mixin background($color) {
    $colorwithout: str-replace(to-string($color), '#', '');

    .background-#{$colorwithout} {
        background: #{$color};
    }
}

body {
    @include background(#ccc);
}

Upvotes: 2

Related Questions