使用Mixin Sass从颜色代码创建类

时间:2019-11-14 16:46:07

标签: css sass

我想创建一个带有颜色代码的类,但是我无法拆分颜色代码以仅获取不含#字符的文本。请参阅下面的示例:

.background-ccc {
    background:#ccc;
}

我想这样使用mixin:

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

使用:

@include background(#ccc)

1 个答案:

答案 0 :(得分:2)

在这里: 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);
}